Js question from challenge | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

Js question from challenge

Hello SL, I have a problem with the following code: for(var i = 0; i <= 5; i++) { setTimeout(function(){ console.log(i) }, i * 1000); } This code Outputs 6 6 6 6 6 6 What I do understand is that setTimeout function is a closure, because it is the inner function that accesses the variable i of the outer for loop, creating a function object multiple times. But, what I dont know is what does the second parameter of the setTimeout function mean? i * 1000, I dont know what that does. Also, for the outcome, I suppose setTimeout only makes 6 function objects without executing them, and waits until i is greater than 5, which is 6, and than the for loop stops? The thing which i have the biggest problem with is this i * 1000 parameter. Thanks in advance.

18th Aug 2020, 2:11 PM
David
David - avatar
4 Réponses
+ 3
Second parameter is the "time". How many miliseconds later do u wanna do the task? So if u write 1000 it means 1 second,
18th Aug 2020, 2:20 PM
maf
maf - avatar
+ 2
Its upon you, if u make it so long (multiplying i by 1000 each time) it would make the time long,
18th Aug 2020, 2:24 PM
maf
maf - avatar
+ 1
maf yes i understand that, i am just confused about why it is multiplied with i
18th Aug 2020, 2:22 PM
David
David - avatar
0
i*1000 mean there console i++ after i seconds Each time
18th Aug 2020, 2:22 PM
Divya Mohan
Divya Mohan - avatar