Sawyer
Sawyer

Reputation: 15917

Javascript Closure question

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.

Upvotes: 0

Views: 133

Answers (1)

Matt
Matt

Reputation: 44058

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
    })();
}
})();

Upvotes: 7

Related Questions