Skip to content Skip to sidebar Skip to footer

How To Control SetTimeout With Promises

var functionsArray = [ function() { setTimeout(function() { console.log(1); }, 100); }, function() { setTimeout(function() { console.log(2);

Solution 1:

You can't get a promise from a function that just calls setTimeout - it needs some help, e.g.:

function after(n, f) {
  return () => new Promise(resolve => {
    setTimeout(() => {
        resolve(f());
    }, n);
  });
}

with usage:

var functionsArray = [
  after(100, () => console.log(1)),
  after(200, () => console.log(2)),
  after( 10, () => console.log(3)),
];

With that array you can then just await each function in turn:

for (let f of functionsArray) {
  await f();
}

Solution 2:

You can write an simple setTimeoutPromise function:

function timeoutPromise(time = 0){
  return new Promise(resolve => setTimeout(resolve, time)
} 


await timeoutPromise(10);
console.log('waited 10 sec')
timeoutPromise(20).then(() => console.log('waited 20 sec')

//make a new array as you like

Promise.all([
 timeoutPromise(100).then(() => console.log(1)),
 timeoutPromise(200).then(() => console.log(2)),
 timeoutPromise(300).then(() => console.log(3))
])

Post a Comment for "How To Control SetTimeout With Promises"