How to activate two JavaScript functions in parallel?
Anyone can tell me how t开发者_如何学编程o activate two (or more) JavaScript AJAX functions in parallel?
This is not possible. Javascript can only work in a single thread and there is no way to actually have two functions running in parallel. You need to make one call and then the other. The callbacks of these will be called (not necessarily in the same order with the invocation methods), when data have been returned or an error/timeout occurs. Only when one callback completes, will the second one be allowed to run.
Have also in mind that browsers restrict the number of active ajax calls. So, if you try to make too many ajax calls, one might wait (blocking all javascript code) for other calls to complete.
Search for Web Workers. These are kind of a new feature in modern browsers and may not be available in old ones.
Is this what you're looking for?
setTimeout('JsFunction1(val);', 0);
setTimeout('JsFunction2(val);', 0);
use Web Workers to run tasks in Parallel
You can a tutorial here: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
Also, this library, which takes advantage of web workers, came up pretty fast on google: https://parallel.js.org/
Using several 'setInterval' may make parallel running possible, though it may still run on a single core. The following code is an example of parallelizing a function func with an array of data 'datas'. To run it, use Parallel(func,datas) where func is the name of your global function and datas is an array of data each one as an input for func.
var i_array=new Array();
function Parallel(func,datas){
$(datas).each(function(i,v){
i_array[i]=setInterval(function(){
clearInterval(i_array[i]);
window[func](datas[i]);
},10);
});
}
Here is a jsfiddle test. The time stamp in integer numbers show the two ajax were running in parallel.
Use window.open() to call a new page. That page will call the first js function. After window.open() calls the second function, you are not technically waiting for the first function to complete. You just wait for the window.open() to execute and then the second will get execute.
Javascript runs as a single thread, if the requests that you want to make doesn't have an IO, In that case its just not possible, if there's an IO operation involved, you can very well execute the two functions one after the other, the very nature of javascript will start executing the next function when it waits for IO. Usually in languages that support threading the same thing is achieved automatically during the CPU rest period for a thread.
精彩评论