有没有办法检查var是否正在使用setInterval()? [英] Is there a way to check if a var is using setInterval()?

查看:139
本文介绍了有没有办法检查var是否正在使用setInterval()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我设置的间隔类似于

For instance, I am setting an interval like

timer = setInterval(fncName, 1000);

如果我去做

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.

推荐答案

没有直接的方法来做你想要的。相反,每次调用 clearInterval 时,您可以将计时器设置为false:

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

这篇关于有没有办法检查var是否正在使用setInterval()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆