在clearInterval之后执行代码
我有一个 setInterval
调用一个显示动画的循环。
当我 clearInterval
响应用户输入时,队列中可能有一个或多个循环回调。如果我直接在 clearInterval
语句之后放置函数调用,则函数调用首先完成(将某些内容打印到屏幕上),然后执行排队循环回调,删除我想要打印的内容。
请参阅下面的代码。
function loop() {
// print something to screen
}
var timer = setInterval(loop(), 30);
canvas.onkeypress = function (event) {
clearInterval(timer);
// print something else to screen
}
处理这个问题的最佳方法是什么?延迟 // 在屏幕上打印其他内容
?在循环内进行新的打印?
编辑:感谢您的回答。为了将来的参考,我的问题是触发额外打印的事件被隐藏在循环中,因此一旦执行,控制权就会交回给未完成的循环,然后覆盖它。干杯。
I have a setInterval
calling a loop which displays an animation.
When I clearInterval
in response to a user input, there are possibly one or more loop callbacks in queue. If I put a function call directly after the clearInterval
statement, the function call finishes first (printing something to screen), then a queued loop callback executes, erasing what I wanted to print.
See the code below.
function loop() {
// print something to screen
}
var timer = setInterval(loop(), 30);
canvas.onkeypress = function (event) {
clearInterval(timer);
// print something else to screen
}
What's the best way to handle this? Put a delay on the // print something else to screen
? Doing the new printing within the loop?
Edit: Thanks for the answers. For future reference, my problem was that the event that triggered the extra printing was buried within the loop, so once this executed, control was handed back to the unfinished loop, which then overwrote it. Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以使用标志来忽略任何排队的函数:
You could also use a flag so as to ignore any queued functions:
首先,您可能的意思是:
其次,您确定调用
clearInterval
不会清除待处理的loop()
调用队列吗?如果是这种情况,您可以使用某种防护措施轻松禁用这些调用:First of all, you probably meant:
Secondly, are you sure calling
clearInterval
does not clean the queue of pendingloop()
calls? If this is the case, you can easily disable these calls by using some sort of guard: