setTimeout()的问题 [英] Problem with setTimeout()
问题描述
这是我的代码。我想要它做的是写0,等待一秒,写1,等待一秒,写2,等待一秒等。相反它写5 5 5 5 5
This is my code. What I want it to do is write 0, wait one sec, write 1, wait one sec, write 2, wait one sec, etc. Instead it writes 5 5 5 5 5
for(i = 0; i < 5; i++) {
setTimeout("document.write(i + ' ')", 1000);
}
推荐答案
1)你全部设置超时同时持续1秒。循环不等待超时发生。所以你有5次超时都在同一时间执行。
1) You set all the timeouts to last 1 second at the same time. The loop doesn't wait for the timeout to occur. So you have 5 timeouts that all execute at the same time.
2)当超时执行时,循环很长,因为完成并且 i
已成为5.所以一旦执行,它们都会打印5
2) When the timeouts execute, the loop is long since complete and i
has become 5. So once they execute, they all print "5"
3) document.write()
将somthing写入页面,在它执行的相同位置。即如果您在一段文本中间有< script> document.write(xyz)< / script>
,它会写入xyz文本的中间部分。但是,超时不一定在页面上的任何位置。它们只存在于代码中。
3) document.write()
writes somthing onto the page, in the same place it executes. I.e. if you have <script>document.write("xyz")</script>
in the middle of a piece of text, it'll write "xyz" in the middle of the text. The timeouts, however, are not necessarily anywhere on the page. They exist only in code.
这是一个尽可能接近你的解决方案: http://jsfiddle.net/rvbtU/1/
Here's a solution that's as close to yours as possible: http://jsfiddle.net/rvbtU/1/
var container = document.getElementById("counter");
for(i = 0; i < 5; i++) {
setTimeout("container.innerHTML += '" + i + " ';", 1000 * i);
}
但是,该解决方案使用setTimeout将字符串计算为javascript的能力,这是从来不是一个好主意。
However, that solution uses setTimeout's ability to evaluate a string as javascript, which is never a good idea.
这是一个使用任何函数的解决方案: http ://jsfiddle.net/YbPVX/1/
Here's a solution that uses an anymous function instead: http://jsfiddle.net/YbPVX/1/
var container = document.getElementById("counter");
var writer = function(number) {
return function() { container.innerHTML += String(number) + " "; };
}
for(i = 0; i < 5; i++) {
setTimeout(writer(i), 1000 * i);
}
编辑:忘记保存第二小提琴。哎呦。现在修复。
Forgot to save the 2nd fiddle. Whoops. Fixed now.
这篇关于setTimeout()的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!