File tree 1 file changed +9
-8
lines changed
1 file changed +9
-8
lines changed Original file line number Diff line number Diff line change 2
2
// for example 1 after 1sec, 2 after 2sec, 3 after 3sec and so on upto 5.
3
3
4
4
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 ) ;
9
12
}
10
-
11
13
console . log ( "Hello JavaScript!" ) ;
12
14
}
13
15
x ( ) ;
14
16
15
17
// Notes:
16
18
// 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
18
21
19
-
20
- //⚡ In the next commit we'll see how the same is achived using var.
You can’t perform that action at this time.
0 commit comments