Skip to content

Commit 1d9b7e0

Browse files
committed
added setTimeout example for printing 1 to 5 after each and every second
1 parent 62eed87 commit 1d9b7e0

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

All Lessons/setTimeout.js

+17-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
1+
// print 1 to 5 after each and every second
2+
// for example 1 after 1sec, 2 after 2sec, 3 after 3sec and so on upto 5.
3+
14
function x(){
2-
var i = 10;
3-
setTimeout(function (){
4-
console.log(i);
5-
}, 3000);
5+
for (var i=0; i<5; i++){
6+
setTimeout(function (){
7+
console.log(i);
8+
}, i* 1000);
9+
}
10+
611
console.log("Hello JavaScript!");
712
}
8-
x();
13+
x();
14+
15+
// 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).
19+
20+
// to avoid this we can use block scope variable which has unique value

0 commit comments

Comments
 (0)