简体   繁体   English

Javascript:如何清除非全局(关闭)的setTimeout?

[英]Javascript: How to clear a non-global (closured) setTimeout?

I'm trying to be a good citizen and keep as much out of the global scope as possible. 我想成为一个好公民,并尽可能地远离全球范围。 Is there a way to access setTimeout variables that are not in the global scope? 有没有办法访问不在全局范围内的setTimeout变量?

So that, in this example how would someone cancel 'timer'? 那么,在这个例子中,有人会如何取消'计时器'?

myObject.timedAction = (function(){
    var timer;
        return function(){
            // do stuff

            // then wait & repeat       
            timer = setTimeout(myObject.timedAction,1000);
        };
})();

I've tried clearTimeout(myObject.timedAction.timer,1000); 我试过clearTimeout(myObject.timedAction.timer,1000); (without success), and not sure what else to try. (没有成功),不知道还有什么可以尝试。

You can't unless you have a reference to timer , which you don't because you're declaring it as a variable in a scope. 除非你有timer的引用,否则你不能这样做,因为你将它声明为作用域中的变量。 You can do something like: 你可以这样做:

myObject.timedAction = (function(){
    return function(){
        // do stuff

        // then wait & repeat       
        myObject.timedAction.timer = setTimeout(myObject.timedAction,1000);
    };
})();

clearTimeout(myObject.timedAction.timer);

Note that the above code will only ever allow ONE timer. 请注意,上面的代码只允许一个计时器。 If you need references to more than one timer, it needs to be adjusted. 如果需要引用多个计时器,则需要进行调整。

The whole point is that the inner variables are private, and inaccessible to the outside world. 重点是内部变量是私有的,外部世界无法访问。 SO you have to change your approach a bit: 所以你必须改变一下你的方法:

myObject.timedAction = (function(){
    var timer;
    var result = function(){
        // do stuff
        // then wait & repeat       
        timer = setTimeout(myObject.timedAction,1000);
    };

    result.cancel = function() {
        clearTimeout(timer);
    };

    return result;
})();

myObject.timedAction();       // start it
myObject.timedAction.cancel() // end it

So now the timer is only ever accessed from inside the closure. 所以现在只能从闭包内部访问计时器。 And yes, you can add methods to a function, because JS is awesome. 是的,您可以向函数添加方法,因为JS非常棒。

Put the timer handle in a property in your object: 将计时器句柄放在对象的属性中:

myObject.timedAction = function(){
  // do stuff
  // then wait & repeat
  this.timer = window.setTimeout(function(){ myObject.timedAction(); },1000);
};

Note that you should wrap the call from the timer in a function, so that it's called as a method of your object instead of as a global function, otherwise you won't be able to access your object using this . 请注意,您应该在函数中包含来自计时器的调用,以便将其作为对象的方法而不是全局函数调用,否则您将无法使用this访问对象。

Now you can stop the timer using: 现在您可以使用以下命令停止计时器

window.clearTimeout(myObject.timer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM