The four-digit numbers you are seeing are the return values of setTimeout
, which is a numerical id that you could later use to cancel the timer.
The setTimeout
method sets its argument to be called later, and continues the current function immediately. So your code quickly finishes its for loop, calling setTimeout three times. When that loop is done, k
is 3.
Then, one second later, the timeout fires, and logs k (3
) to the console.
I believe the reason you only see 3
output once is that setTimeout
will only set a single timeout for a given function. You're passing exactly the same function three times. I don't see this behavior specified in the documentation, though, so it may be implementation defined.
I suspect that what you want is to print the three different values of k
after one second. To do that, you actually need to make a different variable, the value of which doesn't change. You can do that with an extra function that returns a function:
var makefunc = function (k2) {
return function() { console.log(k2); };
}
for(var k=0; k<3; k++) {
setTimeout(makefunc(k),1000);
}
Every time makefunc
is called, it creates a new variable (named k2
here, but actually this would work just as well if that variable was named k
). That variable stays alive until the console.log
call one second later.
A more compact way of writing the same thing:
for(var k=0; k<3; k++) {
setTimeout(function(k) { return function() { console.log(k); }; }(k), 1000);
}