Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronous setTimeout + Loop [duplicate]

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 running the innercode in synchronous order.

For example:

for(x=0;x<20;x++) {
setTimeout(doSomething(), 5000);
}


doSomething() {
setTimeout(function() {alert("test")},1000);
}

If I am not mistaken I should see an alert every 6 seconds, for 20 times. However, what happens is that after 6 seconds I see all the alerts at once (or whatever I put into doSomething)

How do I get my for-loop to wait till the innercode is completed?

like image 588
Steven Avatar asked Mar 13 '23 03:03

Steven


1 Answers

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().

like image 197
Gerardo Furtado Avatar answered Mar 20 '23 13:03

Gerardo Furtado