JS setTimeout 不延迟
好吧,伙计们,我正在尝试每隔 1/4 秒左右在我的页面上添加一次数字。因此,更改对用户是可见的。我正在使用 setTimeout,所有计算都正确进行,但没有任何延迟。这是代码:
for(var i = 0; i < 10; i++)
{
setTimeout(addNum(i),250);
}
我还尝试捕获返回值:
for(var i = 0; i < 10; i++)
{
var t = setTimeout(addNum(i),250);
}
我还尝试使用函数语法作为 setTimeout 参数的一部分:
for(var i = 0; i < 10; i++)
{
var t = setTimeout(function(){array[j].innerHTML + 1},250);
}
我还尝试将代码放入字符串中字符串中的函数调用。我永远不能让它拖延。请帮忙!
Alright guys, I'm trying to add numbers on my page every 1/4 second or so. So the change is visible to the user. I'm using setTimeout and all my calculations are occurring correctly but without any delay. Here's the code:
for(var i = 0; i < 10; i++)
{
setTimeout(addNum(i),250);
}
I've also tried capturing the return value:
for(var i = 0; i < 10; i++)
{
var t = setTimeout(addNum(i),250);
}
I've also tried using function syntax as part of the setTimeout params:
for(var i = 0; i < 10; i++)
{
var t = setTimeout(function(){array[j].innerHTML + 1},250);
}
I've also tried putting code in a string & the function call in a string. I can't ever get it to delay. Help Please!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许相反,由于您多次运行相同的方法,您应该使用
setInterval
方法代替? 以下是如何执行此操作的示例。Perhaps instead, since you're running the same method multiple times, you should use the
setInterval
method instead? Here's an example of how you might do that.尝试 setTimeout("addNum(" + i + ")", 250);它不起作用的原因是它评估参数并执行它并将其更改为类似 setTimeout(addNum(i), 250); 的内容;
Try setTimeout("addNum(" + i + ")", 250); the reason its not working is because its evaluating the parameter and executing it and changing it to something like setTimeout(result of addNum(i), 250);
怎么样:
当您执行
setTimeout(addNum(i),250);
时,您立即执行了该函数(函数名称后跟()
将立即执行它并通过1/4 秒后执行的超时的返回值)。因此,在一个循环中,将立即执行所有 10 个操作。这就是你所看到的。捕获返回值
var t = setTimeout(...);
很有帮助,但不适合您的用例;该值为定时器id号,用于取消超时。不确定您的最后一次尝试是什么,尽管它可能是您的
addNum
例程的函数体,因此应用与上面相同的逻辑。How about:
When you did
setTimeout(addNum(i),250);
you executed the function straight away (function name followed by()
will execute it right away and pass the return value to the timeout to be executed 1/4 second later). So in a loop that would just execute all 10 immediately. Which is what you saw.Capturing the return value
var t = setTimeout(...);
is helpful, but not in your use case; the value is the timer id number, used for cancelling the timeout.Not sure what your last attempt is, although presumably it's the function body of your
addNum
routine, so the same logic applies as above.