Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...