views:

49

answers:

1

Why the following code prints "0 5 10 15 20 ... 100"?

(function () {
for ( var i = 100; i >= 0; i -= 5) {
    (function() {
        var pos = i;
        setTimeout(function() {
            console.log(" pos = " + pos);
        }, (pos + 1)*10);
    })();
}
})();

I declare pos = i , which should be in a descending order. This code originated from John Resig' fadeIn() function in his book Pro javascript techniques.

+7  A: 

You're registering the timeouts in the correct order, the problem is they're timed in order of their value, so value 10 will be printed in 100ms, value 100 in 1000ms, etc.

So you need to change the timing calculation to subtract from the max value (in this case, 100)

(function () {
for ( var i = 100; i >= 0; i -= 5) {
    (function() {
        var pos = i;
        setTimeout(function() {
            console.log(" pos = " + pos);
        }, (100 - pos + 1)*10); // note the subtraction here
    })();
}
})();
Matt