This loop is in a function and it counts down from 10, however if I alert the parameter passed using i in the setV function it actually counts up!
for (var i=10;i>0;i--){
setTimeout('setV('+i+',"Out")',100);
}
function setV(c,t){
alert(c);
}
All the setV are programmed to execute at the same time (100ms after the instaneous loop execution), the order isn't determined (see the spec).
You probably wanted
for (var i=10;i>0;i--){
setTimeout('setV('+i+',"Out")',100*(11-i));
}
When all of the timeouts are set to run at the same time, there is no promise what order they will run this.
This is a much better way to write that loop:
function initThis() {
var idx = 0;
function doOneIteration() {
window.alert(idx);
idx++;
if (idx <= 10) {
window.setTimeout(doOneIteration);
}
}
doOneIteration(); // Start loop
}
initThis(); // This makes it all happen
alert(i), it doesn't count up. It should give you0for every alert, because that's the value ofiwhen the setTimeout callbacks run.i. Unless I'm misunderstanding the point.i.