Can I see if a timer is still running?
What 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 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!');
}