Хотя цикл не задерживает функцию, вам нужно использовать setTimeout в withDelay()
, и она работает нормально
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)
}
Пример вызова функций в строке после задержки.На вопрос спрашивающего.
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);