Skip to content

Commit d0b0c9a

Browse files
committed
fixed #2, by using var with a closure function
1 parent 726e48f commit d0b0c9a

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

All Lessons/setTimeout.js

+9-8
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,20 @@
22
// for example 1 after 1sec, 2 after 2sec, 3 after 3sec and so on upto 5.
33

44
function x(){
5-
for (let i=1; i<=5; i++){
6-
setTimeout(function (){
7-
console.log(i);
8-
}, i* 1000);
5+
for (var i=1; i<=5; i++){
6+
function closure(i){
7+
setTimeout(function (){
8+
console.log(i);
9+
}, i * 1000);
10+
}
11+
closure(i);
912
}
10-
1113
console.log("Hello JavaScript!");
1214
}
1315
x();
1416

1517
// Notes:
1618
// now the code print 1 till 5, for each second
17-
// Because the let variables have block scope and the closure of calling function refers to unique value of i each and every itteration.
19+
// Because the function closure() creates a new copy each time by passing i into closure(i),
20+
// every time we call this closure() function with 'i' it creates new copy of the funtion and refers to that copy for every itteration
1821

19-
20-
//⚡ In the next commit we'll see how the same is achived using var.

0 commit comments

Comments
 (0)