设置超时时出现JavaScript闭合循环问题 [英] JavaScript closure loop issue in set time out
问题描述
我在教程中找到了一些示例(说这是规范示例)
I've found some example in a tutorial (said it was the canonical example)
for (var i=1; i<=5 ; i++) {
setTimeout(function() {
console.log("i: " + i);
}, i*1000);
}
现在,我了解到,闭包将当前作用域传递给该函数,并且我假定它应该输出1,2,3,4,5.但是,它会打印5次数字6.
我在chrome调试器中运行它,首先它在执行循环过程中不执行i值递增的过程而没有进入函数,只有在此之后,它才进入内部函数并执行5次.
我不确定为什么这样做,因为闭包将当前作用域传递给函数,但是为什么每次循环迭代时它都不执行?
Now, I understand that, closure passes in the current scope in to the function, and I assume that it should output 1,2,3,4,5. But instead, it prints number 6 five times.
I ran it in the chrome debugger, and first it goes through the loop without going in to the function while doing the increment of the i value and only after that, it goes in to the inner function and execute it 5 times.
I'm not sure why its doing that, I know, the current scoped is passed in to the function because of closure, but why does it not execute each time the loop iterate?
推荐答案
到超时运行时, for
循环已完成,并且 i
为6,即为什么您得到看到的输出.您需要在循环中捕获 i
:
By the time the timeout runs, the for
loop has finished, and i
is 6, that's why you're getting the output you see. You need to capture i
during the loop:
for (var i=1; i<=5 ; i++) {
(function(innerI) {
setTimeout(function() {
console.log("i: " + innerI);
}, innerI*1000);
})(i);
}
这会创建一个具有自己参数( innerI
)的内部函数,该内部函数会立即被调用,从而捕获 i
的值以在超时时间内使用.
This creates an inner function with it's own parameter (innerI
), that gets invoked immediately and so captures the value of i
for use within the timeout.
这篇关于设置超时时出现JavaScript闭合循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!