Skip to content

Angular 4 setTimeout() with variable delay and wait

I have a list of events with timestamp. What I want is to display the events based on the timestamp:

To add a delay:

delay = timestamp(t+1) - timstamp(t)

I know this doesn’t work well with setTimeout, but there is an workaround, if the timeout is constant, in my case is not.

Is it possible to make the next setTimeout() wait for the previous one? To be specific, if the first setTimeout() has a 5 second delay and the second one has 3 seconds, the second one will appear first. I want them to be in the same order but execute one after the other.

This example works for a constant delay, but I want to calculate the delay based on the information I take iterating the list.

for (i = 1; i <= 5; ++i) {
  setDelay(i);
}

function setDelay(i) {
  setTimeout(function(){
    console.log(i);
  }, 1000);
}

Answer

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.