The code seems to work fine.
But if you are rather trying to understand it, you can end up picking up an import trade of JS.. Closures
So first run it like this
for ( var d = 0; d < 3; d++ )
setTimeout(function() {
console.log( "Value of d: ", d );
console.log( d == d, "Check the value of d." );
}, d * 200);
The output :
Value of d: 3
true "Check the value of d."
Value of d: 3
true "Check the value of d."
Value of d: 3
true "Check the value of d."
Did you notice the non incremented value of d
? This is because the value of d
becomes 3 before any of the setTimeout function is actually executed. So what you need are three copies of d
with the value 1,2,3.
This can be achieved with executing an immediate function & saving the value of d
at the time of defining the setTimeout function itself. What we essentially do is wrap each call inside a scope where d
is accessible later (after setTimeout functions kick off).
Hence your code:
for ( var d = 0; d < 3; d++ ) (function(d) {
setTimeout(function() {
console.log( "Value of d: ", d );
console.log( d == d, "Check the value of d." );
}, d * 200);
})(d);
produces output :
Value of d: 0
true "Check the value of d."
Value of d: 1
true "Check the value of d."
Value of d: 2
true "Check the value of d."