Javascript:如何清除非全局(封闭)setTimeout?
我正在努力成为一个好公民,并尽可能远离全球范围。有没有办法访问不在全局范围内的 setTimeout 变量?
那么,在这个例子中,人们将如何取消“计时器”?
myObject.timedAction = (function(){
var timer;
return function(){
// do stuff
// then wait & repeat
timer = setTimeout(myObject.timedAction,1000);
};
})();
我尝试了 clearTimeout(myObject.timedAction.timer,1000);
(没有成功),但不确定还可以尝试什么。
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?
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);
(without success), and not sure what else to try.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非您有对
timer
的引用,否则您不能这样做,但您没有引用,因为您将其声明为作用域中的变量。您可以执行以下操作:请注意,上述代码将只允许一个计时器。如果您需要引用多个计时器,则需要对其进行调整。
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. You can do something like: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.
重点是内部变量是私有的,外部世界无法访问。所以你必须稍微改变一下你的方法:
所以现在只能从闭包内部访问计时器。是的,您可以向函数添加方法,因为 JS 很棒。
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:
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.
将计时器句柄放在对象的属性中:
请注意,您应该将计时器的调用包装在函数中,以便将其作为对象的方法而不是全局函数进行调用,否则您将无法使用
this
访问您的对象。现在您可以使用以下命令停止计时器:
Put the timer handle in a property in your object:
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
.Now you can stop the timer using: