Skip to content

Commit 3fde1b3

Browse files
committed
closure setTimeout - famous problem
1 parent 386be8e commit 3fde1b3

File tree

1 file changed

+42
-11
lines changed

1 file changed

+42
-11
lines changed

Javascript/js-basics/Closure/closure-setTimeout-MOST-POPULAR.js

+42-11
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
const arr = [10, 20, 30, 40];
1+
const arr = [10, 20, 30, 40]
22

33
for (var i = 0; i < arr.length; i++) {
44
setTimeout(() => {
5-
console.log("Index: " + i + ", element : " + arr[i]);
6-
}, 1000);
5+
console.log("Index: " + i + ", element : " + arr[i])
6+
}, 1000)
77
}
88

99
/* output -
@@ -25,7 +25,7 @@ The variable i is actually declared within the for loop and the inner function a
2525
2626
*/
2727

28-
//SOLUTION - 1 - To print all number from 0..4 after 1000 ms
28+
//SOLUTION - 1 - To print all number from 0..4 after 1000 ms - use let instead of var
2929

3030
// const arr1 = [10, 12, 15, 21];
3131

@@ -41,20 +41,20 @@ The variable i is actually declared within the for loop and the inner function a
4141

4242
// SOLUTION - 2 - To print all number from 0..4 after 1000 ms
4343

44-
const arr2 = [10, 12, 15, 21];
44+
const arr2 = [10, 12, 15, 21]
4545

4646
for (var i = 1; i <= arr2.length; i++) {
4747
// pass in the variable i so that each function
4848
// has access to the correct index
4949

5050
setTimeout(
51-
(function(i_local) {
52-
return function() {
53-
console.log("The index of this number is " + i_local);
54-
};
51+
(function (i_local) {
52+
return function () {
53+
console.log("The index of this number is " + i_local)
54+
}
5555
})(i),
56-
i * 1000
57-
);
56+
i * 1000,
57+
)
5858
}
5959

6060
/*
@@ -70,3 +70,34 @@ Further Reading -
7070
1. https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb
7171
7272
*/
73+
74+
// SOLUTION - 3 - Use different iterator variable i and j
75+
76+
for (var i = 1; i <= 3; i++) {
77+
setTimeout(function () {
78+
console.log(`i: ${i}`)
79+
}, i * 1000)
80+
}
81+
82+
/* OUTPUT
83+
84+
i: 4
85+
i: 4
86+
i: 4
87+
88+
The reason the result gives 4,4,4 instead of 1,2,3 is because i is only one variable, and as we studied earlier, closure preserves access to variables (not value), so it preserves the value of the last instance of i.e. 4.
89+
90+
To receive 3 different values, we needed 3 different variables, which can be achieved by using a block scoped declaration */
91+
92+
for (var i = 1; i <= 3; i++) {
93+
let j = i
94+
setTimeout(function () {
95+
console.log(`j: ${j}`)
96+
}, j * 1000)
97+
}
98+
99+
/* OUTPUT -
100+
j: 1
101+
j: 2
102+
j: 3
103+
It preserves separate values of j in each iteration. j runs every time as the loop iterates New j is created in every iteration */

0 commit comments

Comments
 (0)