Search This Blog

2024/03/24

Javascript: Behaviour of settimeout inside for loop.

Lets consider behaviour of settimeout inside for loop.
Below are code & there output to observe for.


Code Snippet 1:

console.log("Using var");
for (var id = 1; id <=3; id++) {
// The setTimeout function uses a callback, and by the time the callback is executed,
// the loop has already completed, so 'id' will always be 3 in all setTimeout callbacks.
setTimeout(function () {
console.log("seconds: " + id);
}, id * 1000);
}

Output:

Using var
seconds: 4
seconds: 4
seconds: 4


Code Snippet 2:

console.log("Using let from ES6");
for (let id = 1; id <= 3; id++) {
// The use of 'let' creates a block-scoped variable, fixing the closure issue.
// Now each setTimeout callback captures the correct value of 'id'.
setTimeout(function () {
console.log("seconds: " + id);
}, id * 1000);
}

Output:

Using let from ES6
seconds: 1
seconds: 2
seconds: 3


Code Snippet 3:

console.log("Using Immediately Invocable function");
for (var id = 1; id <= 3; id++) {
// Using an immediately-invoked function expression (IIFE) to create a new scope for each iteration.
// This helps avoid the closure issue with setTimeout.
(function (id) {
setTimeout(function () {
console.log("seconds: " + id);
}, id * 1000);
})(id);
}


Output:
Using Immediately Invocable function
seconds: 1
seconds: 2
seconds: 3

No comments:

Post a Comment