Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I see if a timer is 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.

like image 761
Andrew Avatar asked Jul 14 '10 14:07

Andrew


People also ask

How do I know if setInterval is running?

To check if a setInterval timer is running and stop it with JavaScript, we can call clearIntveral with the timer variable. to add a button. to call setInterval with a callback that runs every 2 seconds. Then we select the button with querySelector .

How do I clear set timeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

Is there a timer in JavaScript?

There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.


2 Answers

What I do is:

var timer = null;  if (timer != null) {   window.clearTimeout(timer);    timer = null; } else {   timer = window.setTimeout(yourFunction, 0); } 
like image 66
Benny Neugebauer Avatar answered Oct 12 '22 22:10

Benny Neugebauer


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.

like image 21
tvanfosson Avatar answered Oct 12 '22 22:10

tvanfosson