You have two different issues going on in your code:
- Closures are causing the value
1000
to printed always instead of 100
, 200
... etc.
- The timeouts you are using are too short, so the functions are executing rapidly in succession.
The first problem is hard to explain in a single answer but I will try to give you some insights, since the function that is printing the value of the variables to the console is defined inside the for loop, that function will always keep the value of i
that was there when the loop ended, and in your situation this is 1000
.
To solve this problem, you need something similar to what @thg435 referred to in his comment, something like this:
// this will run a callback function after waiting milliseconds
function waitFor(milliseconds, callback) {
setTimeout(callback, milliseconds);
}
function createFunction(i) {
return function() { console.log(i); };
}
for (var i = 0; i < 1000; i += 100) {
waitFor(i, createFunction(i));
}
The second problem is that the values for the timeout are actually the values that i
take as it is looping which are 100
, 200
... etc which are all very small values less than a second, so when the for loop finishes, those functions will all be ready to executed so they will get executed immediately one after the other.
To solve this issue you need to use a bigger time gap by multiplying i
by 10
for example, like the following:
waitFor(i*10, createFunction(i));
^^^^