Javascript 我可以查看计时器是否仍在运行吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3247173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I see if a timer is still running?
提问by Andrew
Simple question here that I can't seem to find an answer for: Once a setTimeoutis set, is there any way to see if it's still, well, set?
在这里我似乎找不到答案的简单问题:一旦setTimeout设置了 a ,有没有办法查看它是否仍然设置?
if (!Timer)
{
Timer = setTimeout(DoThis,60000);
}
From what I can tell, when you clearTimeout, the variable remains at its last value. A console.logI just looked at shows Timeras being '12', no matter if the timeout has been set or cleared. Do I have to null out the variable as well, or use some other variable as a boolean saying, yes, I have set this timer? Surely there's a way to just check to see if the timeout is still running... right? I don't need to know how long is left, just if it's still running.
据我所知,当你clearTimeout,变量保持在它的最后一个值。Aconsole.log我只是将显示Timer视为“12”,无论超时是否已设置或清除。我是否也必须将变量清零,或者使用其他变量作为布尔值,是的,我已经设置了这个计时器?当然有一种方法可以检查超时是否仍在运行......对吗?我不需要知道还剩多久,只要它仍在运行。
采纳答案by tvanfosson
There isn't anyway to interact with the timer except to start it or stop it. I typically null the timer variable in the timeout handler rather than use a flag to indicate that the timer isn't running. There's a nice description on W3Schoolsabout how the timer works. In their example they use a flag variable.
除了启动或停止它之外,没有任何方法可以与计时器进行交互。我通常将超时处理程序中的计时器变量设为 null,而不是使用标志来指示计时器未运行。W3Schools上有一个关于计时器如何工作的很好的描述。在他们的例子中,他们使用了一个标志变量。
The value you are seeing is a handleto the current timer, which is used when you clear (stop) it.
您看到的值是当前计时器的句柄,在您清除(停止)它时使用。
回答by Benny Neugebauer
What I do is:
我要做的是:
var timer = null;
if (timer != null) {
window.clearTimeout(timer);
timer = null;
}
else {
timer = window.setTimeout(yourFunction, 0);
}
回答by Kapilrc
There is no need to check for an existing timer, just execute clearTimeoutbefore starting the timer.
无需检查现有计时器,只需clearTimeout在启动计时器之前执行即可。
var timer;
//..
var startTimer = function() {
clearTimeout(timer);
timer = setTimeout(DoThis, 6000);
}
This will clear any timer before starting a new instance.
这将在启动新实例之前清除所有计时器。
回答by KDawg
Set another variable Timer_Started = truewith your timer. And also change the variable to falsewhen the timer function is called:
Timer_Started = true用你的计时器设置另一个变量。并且还将变量更改false为调用计时器函数时:
// set 'Timer_Started' when you setTimeout
var Timer_Started = true;
var Timer = setTimeout(DoThis,60000);
function DoThis(){
// function DoThis actions
//note that timer is done.
Timer_Started = false;
}
function Check_If_My_Timer_Is_Done(){
if(Timer_Started){
alert("The timer must still be running.");
}else{
alert("The timer is DONE.");
}
}
回答by zanetu
I usually nullify the timer:
我通常使计时器无效:
var alarm = setTimeout(wakeUpOneHourLater, 3600000);
function wakeUpOneHourLater() {
alarm = null; //stop alarm after sleeping for exactly one hour
}
//...
if (!alarm) {
console.log('Oops, waked up too early...Zzz...');
}
else {
console.log('Slept for at least one hour!');
}
回答by Phil Andelhofs
I know this is a necroposting but i think still people are looking for this.
我知道这是一个 necroposting 但我认为仍然有人在寻找这个。
This is what i use: 3 variables:
这就是我使用的:3 个变量:
tfor milliseconds since.. in Date Object for next targettimerSysfor the actual intervalsecondsthreshold for milliseconds has been set
t几毫秒以来......在下一个目标的日期对象中timerSys对于实际间隔seconds已设置毫秒阈值
next i have a function timerwith 1 variable the function checks if variable is truly, if so he check if timer is already running and if this is the case than fills the global vars, if not truly, falsely, clears the interval and set global var timerSysto false;
接下来我有一个function timer带有 1 个变量的函数检查变量是否是真的,如果是,他检查计时器是否已经在运行,如果是这种情况 ,则填充全局变量,如果不是真的,则错误地清除间隔并设置global var timerSys为假;
var t, timerSys, seconds;
function timer(s) {
if (s && typeof s === "number") {
if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
timerSys = setInterval(function() {
sys();
}, s);
t = new Date().setMilliseconds(s);
seconds = s;
}
} else {
clearInterval(timerSys);
timerSys = false;
}
return ((!timerSys) ? "0" : t)
}
function sys() {
t = new Date().setMilliseconds(seconds);
}
Example I
例一
Now you can add a line to sys function:
现在您可以在sys 函数中添加一行:
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + new Date(t));
//this is also the place where you put functions & code needed to happen when interval is triggerd
}
And execute :
并执行:
timer(5000);
Every 5 seconds in console:
在控制台中每 5 秒:
//output:: Next execution: Sun May 08 2016 11:01:05 GMT+0200 (Romance (zomertijd))
Example II
例二
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + seconds/1000 + " seconds");
}
$(function() {
timer(5000);
});
Every 5 seconds in console:
在控制台中每 5 秒:
//output:: Next execution: 5 seconds
Example III
例三
var t, timerSys, seconds;
function timer(s) {
if (s && typeof s === "number") {
if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
timerSys = setInterval(function() {
sys();
}, s);
t = new Date().setMilliseconds(s);
seconds = s;
}
} else {
clearInterval(timerSys);
timerSys = false;
}
return ((!timerSys) ? "0" : t)
}
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + seconds / 1000 + " seconds");
}
$(function() {
timer(5000);
$("button").on("click", function() {
$("span").text(t - new Date());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Freebeer</button>
<span></span>
Note this way you can go below 0
注意这种方式你可以低于0

