【问题标题】:javascript check setTimeout is running [duplicate]javascript检查setTimeout正在运行[重复]
【发布时间】:2014-01-14 07:11:07
【问题描述】:
function TimerSystem() {
    this.timer = null;

    this.addTimer = function(timer, delay) {
        this.timer = timer;

        setTimeout(function() {
            timerSystem.timer = null;
        }, delay);
    };
}
var timerSystem = new TimerSystem();


timerSystem.addTimer(setTimeout(function() {
            //do something...
        }, 1000), 1000);

它在我的源代码中工作。 让我知道这种方式是否正确? 我认为这不聪明

【问题讨论】:

    标签: javascript settimeout


    【解决方案1】:

    记住timeoutId,当timer func运行时设置为null,如下:

    function schedule(func, millsecs) {
    
        var timeId = setTimeout(function() {
    
            //the function runed, clear this timeId
            timeId = null;
    
            func();
    
        }, millsecs);
    
        return {
    
            isrunning : function() {
    
                return timeId != null;
            }
        };
    }
    
    var sinfo = schedule(function() {
    
        console.log('done');
    
    }, 500);
    
    console.log('just now', sinfo.isrunning());
    

    http://jsfiddle.net/rooseve/AVna6/1/

    另外,为什么需要“检查 setTimeout 是否正在运行”?

    【讨论】:

    • 我想在计时器运行时阻止用户输入。谢谢! :)
    猜你喜欢
    • 2013-04-04
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多