Skip to content Skip to sidebar Skip to footer

Synchronous SetTimeout + Loop

Situation: I have X (0-20) Images that need to be shown in order with a delay between each of them. I tried to implement that with a for-loop and setTimeout but struggle with runn

Solution 1:

This is the expected behaviour in JavaScript. Your first function will loop to the end almost immediately, not in 5000*20 milliseconds.

This is what you can do: create a IIFE with a setTimeout inside:

var i = 0;
(function loop(){
  if (i++ > 20) return;
  setTimeout(function(){
    alert("hi");
    loop();
  }, 5000);
})();

Here is the fiddle:https: https://jsfiddle.net/f6ztxmgp/1/

You can simple change the alert("hi") part to doSomething().


Post a Comment for "Synchronous SetTimeout + Loop"