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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With