Skip to content

Commit 726e48f

Browse files
committed
fixed #1, by using let for its block scope
1 parent 1d9b7e0 commit 726e48f

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

All Lessons/setTimeout.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// for example 1 after 1sec, 2 after 2sec, 3 after 3sec and so on upto 5.
33

44
function x(){
5-
for (var i=0; i<5; i++){
5+
for (let i=1; i<=5; i++){
66
setTimeout(function (){
77
console.log(i);
88
}, i* 1000);
@@ -13,8 +13,8 @@ function x(){
1313
x();
1414

1515
// Notes:
16-
// the following code doesnt work it only prints 5,5,5,5,5
17-
// Because till it waits for 1sec the value of i has become 5
18-
// and since each time the i is refered to the same memory the latest value is 5(because of closure).
16+
// 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.
1918

20-
// to avoid this we can use block scope variable which has unique value
19+
20+
//⚡ In the next commit we'll see how the same is achived using var.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy