Skip to content
Advertisement

Is there a way to check if a var is using setInterval()?

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.

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement