Javascript关闭问题

Saw*_*yer 0 javascript closures

为什么以下代码打印"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);
    })();
}
})();
Run Code Online (Sandbox Code Playgroud)

我声明pos = i,它应该是降序.此代码源自John Resig的fadeIn()函数,在他的书籍Pro javascript技术中.

Mat*_*att 7

您正在以正确的顺序注册超时,问题是它们按其值的顺序计时,因此值10将以100毫秒打印,值100打印在1000毫秒等.

因此,您需要更改时序计算以从最大值中减去(在本例中为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
    })();
}
})();
Run Code Online (Sandbox Code Playgroud)