如何在按下按键时暂停/播放 Javascript 循环?
使用 Javascript/jQuery,如何暂停(或恢复)以下 当按下“P”键时循环?
(function() {
var arr = [...],
len = arr.length;
(function doProcess(i) {
if (i) {
console.log(len - i);
/* do something with arr[len - i] */
setTimeout(function() { doProcess(--i); }, 20000);
}
})(len);
})();
Using Javascript/jQuery, how can I pause (or resume) the following loop when the "P" key is pressed?
(function() {
var arr = [...],
len = arr.length;
(function doProcess(i) {
if (i) {
console.log(len - i);
/* do something with arr[len - i] */
setTimeout(function() { doProcess(--i); }, 20000);
}
})(len);
})();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
暂停和恢复相当复杂。您真正需要做的是:
这是我编写的一个更通用的 jsFiddle 示例。
Pausing and resuming is fairly complex. What you really have to do is this:
Here's a more generalized jsFiddle example I whipped up.
您需要跟踪计时器已经过去了多少时间(请参阅此处:javascript:pause setTimeout() ;)并对您想要停止的任何事件调用clearTimeout,然后在再次触发任何取消暂停的事件后再次调用setTimeout,并保留剩余时间。
You'll want to keep track of how much time has passed with your timer (see here: javascript: pause setTimeout();) and call clearTimeout on whatever event you want to stop, then call setTimeout again with your remaining time left once whatever event unpauses is fired again.