Skip to content

Commit 393811b

Browse files
Create 11-setTimeout-closures.md
1 parent 72314be commit 393811b

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Notes/11-setTimeout-closures.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Episode 11 : setTimeout + Closures Interview Question
2+
3+
#### Time, tide and Javascript wait for none
4+
5+
```
6+
function x() {
7+
var i = 1;
8+
setTimeout(function() {
9+
console.log(i);
10+
}, 3000);
11+
console.log("This is Hari");
12+
}
13+
x();
14+
15+
```
16+
> This is Hari
17+
18+
> 1 //after waiting 3 seconds (3000ms)
19+
20+
We expect JS to wait 3 sec, print 1 and then go down and print the string. But JS prints string immediately, waits 3 sec and then prints 1.
21+
22+
- The fun inside setTimeout forms a closure (remembers reference to i). So wherever fun goes it carries this ref along with it.
23+
- setTimeout takes this callback function & attaches timer of 3000ms and stores it. Goes to next line without waiting and prints string.
24+
- After 3000ms runs out, JS takes function, puts it into call stack and runs it.
25+
26+
#### Print 1 after 1 sec, 2 after 2 sec till 5 : Tricky interview question
27+
28+
We assume this has a simple approach as below
29+
30+
```
31+
function x() {
32+
for(var i = 1; i<=5; i++){
33+
setTimeout(function() {
34+
console.log(i);
35+
}, i*1000);
36+
}
37+
console.log("This is Hari");
38+
}
39+
x();
40+
41+
```
42+
43+
> This is Hari
44+
45+
> 6
46+
47+
> 6
48+
49+
> 6
50+
51+
> 6
52+
53+
> 6
54+
55+
- This happens because of closures. When setTimeout stores the function somewhere and attaches timer to it, the fun remembers its reference to i, **not value of i**
56+
- All 5 copies of fun point to same reference of i.
57+
- JS stores these 5 functions, prints string and then comes back to the functions. By then the timer has run fully. And due to looping, the i value became 6. And when the
58+
callback fun runs the variable i = 6. So same 6 is printed in each log
59+
- **To stop this from happening, use let instead of var** as let has black scope. For each iteration, the i is a new variable altogether(new copy of i).
60+
- Everytime setTimeout is run, the inside fun forms closure with new variable i
61+
62+
#### Using let instead of var is the best option. But if asked to use var only..?
63+
64+
```
65+
function x() {
66+
for(var i = 1; i<=5; i++){
67+
function close(i) {
68+
setTimeout(function() {
69+
console.log(i);
70+
}, i*1000);
71+
// put the setT fun inside new function close()
72+
}
73+
close(i); // everytime you call close(i) it creates new copy of i. Only this time, it is with var itself!
74+
}
75+
console.log("This is Hari");
76+
}
77+
x();
78+
79+
```
80+

0 commit comments

Comments
 (0)