简体   繁体   中英

Why functionalities runs sequentially even though they are being called asynchronously inside a loop?

I am creating a wrapper function which will take array of functions and executes every function in a parallel manner so thought of using setTimeout but still functions are running sequentially. I suspect it could be because of closure that is being used to call SetTimeout. But why does it matter since setTimeout is async anyway?

// some blocking functionality
var withDelay = function (a) {
   var currentTime = new Date().getTime(), delay = 5000;
   while (currentTime + delay >= new Date().getTime()) {
   }
   console.log(a+"I am with delay");
}

// some non blocking functionality
var withoutDelay = function(a) {
   console.log(a+"I am with no delay");
}

var fnArr = [withDelay, withoutDelay]; //array of functions
var args = ["Hi,"]; // arbitrary params

for( var i=0; i < fnArr.length; i++) {
    var fn = fnArr[i];
    (function(f,arg) {
        return setTimeout(function(){ return f.apply(f,arg) },0);
    })(fn,args)
}

Expected output:

Hi,I am with no delay

Hi,I am with delay

but Actual output is:

Hi,I am with delay

Hi,I am with no delay

JS runs on a single thread, Your function will not run parallelly. It will only run one at a time. Since you have scheduled both the functions with 0 delay as soon the first function from fnArr array viz. withDelay will run first. Only when this will complete its execution, the second function withoutDelay will start its execution. setTimeout will not guarantee your execution after provided interval, it is the minimum interval after which your function will execute. You can read more about setTimeout here

While loop doesnot delay a function you need to use setTimeout in your withDelay() and it working fine

 var withDelay = function (a) { setTimeout(() => {console.log(a+"I am with delay")},5000); } // some non blocking functionality var withoutDelay = function(a) { console.log(a+"I am with no delay"); } var fnArr = [withDelay, withoutDelay]; //array of functions var args = ["Hi,"]; // arbitrary params for( var i=0; i < fnArr.length; i++) { var fn = fnArr[i]; (function(f,arg) { return setTimeout(function(){ return f.apply(f,arg) },0); })(fn,args) } 
An example to call functions in a line after delay. As asked by questioner.

 function func1(){ console.log("Function 1 is executed"); console.timeEnd('t'); } function func2(){ console.log("Function 2 is executed"); console.timeEnd('t'); } function func3(){ console.log("Function 3 is executed"); console.timeEnd('t'); } let arrr = [ {func:func1,delay:2000}, {func:func2,delay:2000}, {func:func3,delay:3000}, ] async function callWithDelay(funcArr){ for(let func of funcArr){ //just to see time in console not necesarry console.time('t'); //create a promise let promise = new Promise((resolve,reject) => { //'promise' will resolve after the function inside following code will end setTimeout(()=> { resolve(); func.func(); },func.delay) }) //The code will not proceed until the 'promise' is resolved(func is excecuted); let x = await promise; } console.log("All the functions are excecuted"); } callWithDelay(arrr); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM