How to activate two JavaScript functions in parallel?

前端 未结 7 843
失恋的感觉
失恋的感觉 2020-12-16 02:23

Anyone can tell me how to activate two (or more) JavaScript AJAX functions in parallel?

相关标签:
7条回答
  • 2020-12-16 02:46

    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/

    0 讨论(0)
  • 2020-12-16 02:46

    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.

    0 讨论(0)
  • 2020-12-16 02:48

    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.

    0 讨论(0)
  • 2020-12-16 02:49

    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.

    0 讨论(0)
  • 2020-12-16 02:52

    Is this what you're looking for?

    setTimeout('JsFunction1(val);', 0); 
    setTimeout('JsFunction2(val);', 0);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题