javascript: 暂停 setTimeout();
如果我有一个通过设置的活动超时正在运行,
var t = setTimeout("dosomething()", 5000)
是否有办法暂停和恢复它?
有什么办法可以获取当前超时的剩余时间吗?
或者我必须在一个变量中,当设置超时时,存储当前时间,然后我们暂停,得到现在和那时之间的差异?
If I have an active timeout running that was set through
var t = setTimeout("dosomething()", 5000)
Is there anyway to pause and resume it?
Is there any way to get the time remaining on the current timeout?
or do I have to in a variable, when the timeout is set, store the current time, then we we pause, get the difference between now and then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
您可以像这样包装
window.setTimeout
,我认为这与您在问题中建议的类似:You could wrap
window.setTimeout
like this, which I think is similar to what you were suggesting in the question:像这样的事情应该可以解决问题。
Something like this should do the trick.
Tim Downs 答案的稍微修改版本。但是,由于蒂姆回滚我的编辑,我必须回答这个我自己。我的解决方案可以使用额外的参数作为第三个参数(3、4、5...)并清除计时器:
正如 Tim 提到的,额外的参数在 IE lt 中不可用9,但是我做了一些工作,以便它也可以在
oldIE
中工作。用法:
new Timer(Function, Number, arg1, arg2, arg3...)
A slightly modified version of Tim Downs answer. However, since Tim rolled back my edit, I've to answer this myself. My solution makes it possible to use extra
arguments
as third (3, 4, 5...) parameter and to clear the timer:As Tim mentioned, extra parameters are not available in
IE lt 9
, however I worked a bit around so that it will work inoldIE
's too.Usage:
new Timer(Function, Number, arg1, arg2, arg3...)
不可以。您需要取消它 (
clearTimeout
),测量自启动以来的时间并使用新时间重新启动它。No. You'll need cancel it (
clearTimeout
), measure the time since you started it and restart it with the new time.超时很容易找到解决方案,但间隔有点棘手。
我想出了以下两个类来解决这个问题:
这些可以这样实现:
这个示例将设置一个可暂停的超时(pt_hey),计划在两秒后发出“嘿”警报。另一次超时在一秒后暂停 pt_hey。两秒后第三次超时恢复 pt_hey。 pt_hey 运行一秒,暂停一秒,然后恢复运行。 pt_hey 在三秒后触发。
现在是更棘手的间隔
此示例设置一个可暂停的间隔 (pi_hey),每两秒在控制台中写入“hello world”。超时会在五秒后暂停 pi_hey。六秒后,另一个超时恢复 pi_hey。所以pi_hey会触发两次,运行一秒,暂停一秒,运行一秒,然后每2秒继续触发一次。
其他函数
clearTimeout()和clearInterval()
pt_hey.clearTimeout();
和pi_hey.clearInterval();
是清除超时和间隔的简单方法。getTimeLeft()
pt_hey.getTimeLeft();
和pi_hey.getTimeLeft();
将返回距离下一次触发计划发生还有多少毫秒。The Timeout was easy enough to find a solution for, but the Interval was a little bit trickier.
I came up with the following two classes to solve this issues:
These can be implemented as such:
This example will set a pauseable Timeout (pt_hey) which is scheduled to alert, "hey" after two seconds. Another Timeout pauses pt_hey after one second. A third Timeout resumes pt_hey after two seconds. pt_hey runs for one second, pauses for one second, then resumes running. pt_hey triggers after three seconds.
Now for the trickier intervals
This example sets a pauseable Interval (pi_hey) to write "hello world" in the console every two seconds. A timeout pauses pi_hey after five seconds. Another timeout resumes pi_hey after six seconds. So pi_hey will trigger twice, run for one second, pause for one second, run for one second, and then continue triggering every 2 seconds.
OTHER FUNCTIONS
clearTimeout() and clearInterval()
pt_hey.clearTimeout();
andpi_hey.clearInterval();
serve as an easy way to clear the timeouts and intervals.getTimeLeft()
pt_hey.getTimeLeft();
andpi_hey.getTimeLeft();
will return how many milliseconds till the next trigger is scheduled to occur.“暂停”和“恢复”在
setTimeout
的上下文中并没有多大意义,这是一次性的事情。您可能想要暂停一系列setTimeout
调用的链式,在这种情况下,只需不要安排下一个调用(也许可以通过clearTimeout<取消未完成的调用) /code>,如下)。但 setTimeout 本身并不循环,没有什么可以暂停和恢复的。
如果您的意思是
setInterval
,那么不,您无法暂停它,只能取消它(clearInterval
),然后再次重新安排。所有这些的详细信息请参见规范的计时器部分。"Pause" and "resume" don't really make much sense in the context of
setTimeout
, which is a one-off thing. You might want to pause a chained series ofsetTimeout
calls, in which case just don't schedule the next one (perhaps cancel the one that's outstanding viaclearTimeout
, as below). ButsetTimeout
itself doesn't loop, there's nothing to pause and resume.If you mean
setInterval
then no, you can't pause it, you can only cancel it (clearInterval
) and then re-schedule it again. Details of all of these in the Timers section of the spec./revive
使用 Class-y 语法糖的 ES6 版本
/revive
ES6 Version using Class-y syntactic sugar ????
(slightly-modified: added start())
基于最高评价答案的打字稿实现
Typescript implementation based on top rated answer
我需要计算已用时间和剩余时间以显示进度条。使用已接受的答案并不容易。对于此任务,“setInterval”比“setTimeout”更好。因此,我创建了这个可以在任何项目中使用的 Timer 类。
https://jsfiddle.net/ashraffayad/t0mmv853/
I needed to calculate the elapsed and remaining time to show a progress-bar. It was not easy using the accepted answer. 'setInterval' is better than 'setTimeout' for this task. So, I created this Timer class that you can use in any project.
https://jsfiddle.net/ashraffayad/t0mmv853/
该程序相当简单。我们将创建一个包含两个函数的类:
pause
函数和unpause
函数。pause
函数将清除setTimeout
并将开始到现在之间经过的时间存储在time_left
变量中。unpause
函数将通过将time_left
时间作为参数来重新创建setTimeout
。The programme is rather simple. We will create a class containing two functions, the
pause
function and theunpause
function.The
pause
function will clear thesetTimeout
and store the time that has elapsed between the start and now in thetime_left
variable. Theunpause
function will recreate asetTimeout
by putting thetime_left
time as an argument.您可以查看 clearTimeout()
或根据设置的全局变量暂停达到一定条件。就像按下按钮一样。
You could look into clearTimeout()
or pause depending on a global variable that is set when a certain condition is hit. Like a button is pressed.
您还可以通过事件来实现它。
您无需计算时间差,而是开始和停止监听在后台持续运行的“tick”事件:
You could also implement it with events.
Instead of calculating the time difference, you start and stop listening to a 'tick' event which keeps running in the background:
如果您无论如何都使用 jquery,请查看 $.doTimeout 插件。这个东西比 setTimeout 是一个巨大的改进,包括让你用你指定的单个字符串 id 来跟踪你的超时,并且每次设置它时都不会改变,并实现简单的取消、轮询循环和超时。去抖动等等。我最常用的 jquery 插件之一。
不幸的是,它不支持开箱即用的暂停/恢复。为此,您需要包装或扩展 $.doTimeout,大概与接受的答案类似。
If you're using jquery anyhow, check out the $.doTimeout plugin. This thing is a huge improvement over setTimeout, including letting you keep track of your time-outs with a single string id that you specify and that doesn't change every time you set it, and implement easy canceling, polling loops & debouncing, and more. One of my most-used jquery plugins.
Unfortunately, it doesn't support pause/resume out of the box. For this, you would need to wrap or extend $.doTimeout, presumably similarly to the accepted answer.
我需要能够暂停 setTimeout() 以实现类似幻灯片的功能。
这是我自己实现的可暂停计时器。它集成了在 Tim Down 的答案中看到的评论,例如更好的暂停(内核的评论)和原型设计的形式(Umur Gedik 的评论)。
示例:
要测试代码,请使用
timer.resume()
和timer.pause()
几次并检查还剩多少时间。 (确保您的控制台已打开。)使用此对象代替 setTimeout() 就像将
timerID = setTimeout( mycallback, 1000)
替换为timer = new Timer( mycallback, 1000) 一样简单)
。然后您可以使用timer.pause()
和timer.resume()
。I needed to be able to pause setTimeout() for slideshow-like feature.
Here is my own implementation of a pausable timer. It integrates comments seen on Tim Down's answer, such as better pause (kernel's comment) and a form of prototyping (Umur Gedik's comment.)
Example:
To test the code out, use
timer.resume()
andtimer.pause()
a few times and check how much time is left. (Make sure your console is open.)Using this object in place of setTimeout() is as easy as replacing
timerID = setTimeout( mycallback, 1000)
withtimer = new Timer( mycallback, 1000 )
. Thentimer.pause()
andtimer.resume()
are available to you.“异步”工作演示位于:
网站 zarsoft.info
"async" working demo at:
site zarsoft.info
您可以像下面一样使 setTimeout 在服务器端(Node.js)可暂停
,并且您可以按如下方式检查它
You can do like below to make setTimeout pausable on server side (Node.js)
and you can check it as below
如果有人想要@SeanVieira 阁下在此处分享的 TypeScript 版本,您可以使用以下命令:
If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:
我在 TypeScript 中为滑块功能创建了以下代码:
I created this code in TypeScript for slider feature:
我认为您不会找到比 clearTimeout 更好的东西了。无论如何,您始终可以稍后安排另一个超时,而不是“恢复”它。
I don't think you'll find anything better than clearTimeout. Anyway, you can always schedule another timeout later, instead 'resuming' it.
如果您有多个要隐藏的 div,您可以使用
setInterval
和多个周期来执行以下操作:If you have several divs to hide, you could use an
setInterval
and a number of cycles to do like in: