Angular 4 setTimeout() with variable delay and wait

When using the latest Typescript or ES code, we can use aync/await for this.

let timestampDiffs = [3, 2, 4];

(async () => {
  for (let item of timestampDiffs) {
    await timeout(item * 1000);
    console.log('waited: ' + item);
  }
})();

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

We need to wrap the for loop in an async immediately invoked function because to support await.

We also do need a timeout function that returns a promise once the timeout is complete.

After that, we wait for the timeout to complete before continuing with the loop.


You can use IIFE (Immediately Invoked Function Expression) and function recursion instead. Like this:

let i = 0;
(function repeat(){
  if (++i > 5) return;
  setTimeout(function(){
    console.log("Iteration: " + i);
    repeat();
  }, 5000);
})();

Live fiddle here.