4

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?

2
  • 2
    or you can do this as well setTimeout(doSomething(), (x+1) * 5000); Commented Jun 1, 2016 at 8:58
  • Your approach will schedule each Timers after 5000 ms of the previous one. Let's assume that first doSomething() took around 7000ms, will the next Timer be delayed because we are in a single threaded environment ? Commented Dec 22, 2016 at 15:26

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Just need a little clarification. His first function doSomething() will be executed immediately. 20 Timers will be setup and each will expire in 5000 ms. Once 5s are gone, functions will start execution. But since we are in a single threaded environment. Each timer will start one by one. Is the understanding correct ?
No, his function doSomething() will not execute immediately, because it is not being called anywhere, except for the timers. The problem here is simply that 20 timers are set at (almost) the same time, and they all fire at (almost) the same time, calling doSomething() 20 times. Here is a good explanation: scottiestech.info/2014/07/01/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.