[SOLVED] For loop with setTimeout | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[SOLVED] For loop with setTimeout

I am trying to work with a for loop that sets a timeout on every string. For example: output first string after 1000ms output second string after 2000ms output third string after 3000ms output fourth string after 4000ms etc.. etc.. I made some code but didn't get it working.. Tried setTimeout inside the loop. And tried to add a function so it loops throught the function. What I am doing wrong🤔 Any help will be appericiated👍 (When solution is given, briefly explained will also be appericiated) https://code.sololearn.com/WWWeQZEoYje2/?ref=app

7th Sep 2018, 11:17 AM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
5 Answers
+ 1
the setTimeout method will run a function after some number of milliseconds, but only after the for loop has stopped executing, by the time the for loop has stopped executing, the value of i is 7. So each time the given function gets called, it will print out undefined because the value of len[7] is undefined so to get around this problem you have two choices either use the IIFE to capture i at each iteration like this: for (var i=0, initialize=len.length; i<initialize; i++) { (function(index){ setTimeout (function() { document.write(" <span id='arrayvalue'>"+len[index]+"</span><br />"); }, 1000 * index); })(i) } or simply use the let keyword instead of var: for (let i=0, initialize=len.length; i<initialize; i++) { setTimeout (function() { document.write(" <span id='arrayvalue'>"+len[i]+"</span><br />"); }, 1000 * i); }
7th Sep 2018, 12:23 PM
MO ELomari
+ 1
replace 2000 by 2000*index
7th Sep 2018, 12:52 PM
MO ELomari
+ 1
increase the time of the execution
7th Sep 2018, 12:58 PM
MO ELomari
0
Mohamed ELomari, Thanks for the extended explanation to my question. But I tried to capture each iteration with a callback function. I tried the let keyword, but i cannot make changes to let when the code it running for later use to my understanding. And tried the first solution you provided. Both will not output first string, then second, then third after x amount of time between every output Both will output the whole variable at once...
7th Sep 2018, 12:49 PM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar
0
What is the reason to use * I do not fully understand that part of the code
7th Sep 2018, 12:55 PM
🌴Vincent Berger🌴
🌴Vincent Berger🌴 - avatar