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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With