For instance, I am setting an interval like
timer = setInterval(fncName, 1000);
and if i go and do
clearInterval(timer);
it does clear the interval but is there a way to check that it cleared the interval? I've tried getting the value of it while it has an interval and when it doesn't but they both just seem to be numbers.
click(function(e) { clearInterval(interval); interval = null; }); And, you don't need to check to see if interval is undefined . You can just call clearInterval() on it and clearInterval() will protect against any invalid argument you pass it.
JavaScript setInterval() method. The setInterval() method in JavaScript is used to repeat a specified function at every given time-interval. It evaluates an expression or calls a function at given intervals. This method continues the calling of function until the window is closed or the clearInterval() method is called ...
setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
The setInterval() returns a numeric, non-zero number that identifies the created timer. You can pass the intervalID to the clearInterval() to cancel the timeout.
There is no direct way to do what you are looking for. Instead, you could set timer
to false every time you call clearInterval
:
// Start timer var timer = setInterval(fncName, 1000); // End timer clearInterval(timer); timer = false;
Now, timer
will either be false or have a value at a given time, so you can simply check with
if (timer) ...
If you want to encapsulate this in a class:
function Interval(fn, time) { var timer = false; this.start = function () { if (!this.isRunning()) timer = setInterval(fn, time); }; this.stop = function () { clearInterval(timer); timer = false; }; this.isRunning = function () { return timer !== false; }; } var i = new Interval(fncName, 1000); i.start(); if (i.isRunning()) // ... i.stop();
The return values from setTimeout
and setInterval
are completely opaque values. You can't derive any meaning from them; the only use for them is to pass back to clearTimeout
and clearInterval
.
There is no function to test whether a value corresponds to an active timeout/interval, sorry! If you wanted a timer whose status you could check, you'd have to create your own wrapper functions that remembered what the set/clear state was.
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