admin管理员组文章数量:1134589
Simple question here that I can't seem to find an answer for: Once a setTimeout
is set, is there any way to see if it's still, well, set?
if (!Timer)
{
Timer = setTimeout(DoThis,60000);
}
From what I can tell, when you clearTimeout
, the variable remains at its last value. A console.log
I just looked at shows Timer
as 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.
Simple question here that I can't seem to find an answer for: Once a setTimeout
is set, is there any way to see if it's still, well, set?
if (!Timer)
{
Timer = setTimeout(DoThis,60000);
}
From what I can tell, when you clearTimeout
, the variable remains at its last value. A console.log
I just looked at shows Timer
as 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.
7 Answers
Reset to default 81What I do is:
var timer = null;
if (timer != null) {
window.clearTimeout(timer);
timer = null;
}
else {
timer = window.setTimeout(yourFunction, 0);
}
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 W3Schools about how the timer works. In their example they use a flag variable.
The value you are seeing is a handle to the current timer, which is used when you clear (stop) it.
There is no need to check for an existing timer, just execute clearTimeout
before starting the timer.
var timer;
//..
var startTimer = function() {
clearTimeout(timer);
timer = setTimeout(DoThis, 6000);
}
This will clear any timer before starting a new instance.
Set another variable Timer_Started = true
with your timer. And also change the variable to false
when the timer function is called:
// 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.");
}
}
I know this is a necroposting but i think still people are looking for this.
This is what i use: 3 variables:
t
for milliseconds since.. in Date Object for next targettimerSys
for the actual intervalseconds
threshold for milliseconds has been set
next i have a function timer
with 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 timerSys
to false;
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:
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:
//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:
//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
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!');
}
I created a timer service as below exported from timer.ts -
import { setIntoStorage } from "./storage";
type TimeoutInfo = {
key: string;
timeOutDate: string;
purpose?: string;
};
const kActiveTimersKey = "app-active-timers";
class Timers {
private static instance: Timers;
private static activeTimers: TimeoutInfo[] = [];
constructor() {
if (Timers.instance) {
return Timers.instance;
}
Timers.instance = this;
}
async addTimeoutEntry(timeoutInfo: TimeoutInfo): Promise<void> {
this.removeTimeoutEntry(timeoutInfo.key);
Timers.activeTimers.push(timeoutInfo);
await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
}
async removeTimeoutEntry(key: string): Promise<void> {
Timers.activeTimers = Timers.activeTimers.filter((v) => v.key !== key);
await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
}
}
export const TimerService = new Timers();
I use this whilst creating or clearing a timeout -
if (timer) {
clearTimeout(timer);
timer = null;
TimerService.removeTimeoutEntry("AUTO_LOGOUT_TIMER");
}
timer = setTimeout(() => {
dispatch(signUserOut());
}, timeoutTime);
const now = new Date();
TimerService.addTimeoutEntry({
key: "AUTO_LOGOUT_TIMER",
timeOutDate: new Date(now.getTime() + timeoutTime).toLocaleString(),
purpose: "Auto logout user when the JWT token expires",
});
A bit of overhead to add/remove to timer service but it shows up in the local storage for a quick check. I have very few use for this service since I don't have much timeouts set in my app.
Showed like this in the indexedDb -
本文标签: javascriptCan I see if a timer is still runningStack Overflow
版权声明:本文标题:javascript - Can I see if a timer is still running? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736862310a1955971.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论