Skip to content

Commit 45b5e7a

Browse files
closures+setTimeout
1 parent e8789b2 commit 45b5e7a

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//To create the setTimeout we need the closures . there is the task to print the numbers 1,2,3 after corresponding seconds means 1 after one second 2 after 2 seconds so on till 5 .To solve this problem we need setTimeout Normal we will do this
2+
function a() {
3+
for (var i = 0; i <= 5; i++) {
4+
setTimeout(() => {
5+
console.log(i)
6+
}, i * 1000)
7+
}
8+
}
9+
a()
10+
//But this will print 6 for 5 times after 1,2,3,4,5 seconds i.e
11+
//after 1 sec 6
12+
//after 2 sec 6
13+
//after 3 sec 6
14+
//after 4 sec 6
15+
//after 5 sec 6
16+
// This is due to closures setTimeout callback function is closured with a function with the variable i which is incrementing due to for loop . javascript will not pause because of this variable i already incremented to 6 till it is stored 5 different callback is created by referencing same variable i.e i which is globally attached to global object that's why it will not treat it as different variable because it is referencing same variable .It is solved by replacing var with let in for loop due to let has block scope it will treat as different value after every iteration which is the power of let .
17+
// Another solution is to wrap up the setTimeout inside another function and pass i in that function through this i variable will treated as different value after every iteration
18+
function a() {
19+
for (var i = 0; i <= 5; i++)
20+
function closure(ivalue) {
21+
setTimeout(() => {
22+
console.log(ivalue)
23+
}, ivalue * 1000)
24+
}
25+
closure(i)
26+
}
27+
a()

0 commit comments

Comments
 (0)