有效使用 setInterval/clearInterval
我正在向我已经开发的应用程序添加新功能。我正在尝试添加自动渲染功能,该功能会在一定时间间隔后自动渲染屏幕的某些部分。我为此使用 setInterval ,一切正常。
我的问题是,我应该如何为除一个事件之外的所有其他事件调用 clearInterval(intervalId) 函数。请考虑一个例子: 假设我有一些与当前屏幕相关的事件,并且我想仅在单击“.myBtn”时启动 setInterval 并停止所有其他事件。
var intervalId = 0;
$(".myBtn").click(function(){
intervalId = setInterval(function(){
alert("execute something");
}, 2000);
});
$(".otherElm").click(function(){
// some other stuff.
});
$(".otherElm1").click(function(){
// some other stuff.
});
$(".otherElm2").click(function(){
// some other stuff.
});
对于上述情况,我只知道一种停止间隔的方法,即在每个其他事件中放置“clearInterval(intervalId)”。
但是,还有其他方法可以做到这一点吗?
希望我已经把所有内容都写好了,以便人们能够理解我的问题。
提前致谢
I am adding new features to my already developed application. I am trying to add an auto rendering functionality which automatically render some part of the screen after a certain time interval. I am using setInterval for this, everything is working fine.
My question is, how should I call the clearInterval(intervalId) function for all other events except one. Please consider an example:
Suppose I have some events related to current screen, and I want to start my setInterval only on ".myBtn" click and stop for all other events.
var intervalId = 0;
$(".myBtn").click(function(){
intervalId = setInterval(function(){
alert("execute something");
}, 2000);
});
$(".otherElm").click(function(){
// some other stuff.
});
$(".otherElm1").click(function(){
// some other stuff.
});
$(".otherElm2").click(function(){
// some other stuff.
});
For the above situation, I know only one way to stop the interval i.e. to put "clearInterval(intervalId)" in every other event.
But, is there any other way to do this?
Hope I have put everything so that one can understand my question.
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的评论是正确的 - 您必须将clearInterval(IntervalId)放入您需要停止事件的所有事件中。这样做有问题吗?
编辑:
用一个类来识别它们 - 比如说榆树。完成此操作后,使用 $(".elm").click(clearinterval)。
You are right in your comment - you have to put clearInterval(IntervalId) into all of the events that you require to stop the event. Is there a problem with doing this?
Edit:
Identify them all with a class - say elm. Once this is done, use $(".elm").click(clearinterval).
另一种方法是执行以下操作:
虽然代码更多,但我发现它更易于管理,特别是如果您最终需要处理大量的intervalID。
Another way to do it would be to do something like:
Although more code, I find it easier to manage, especially if you end up having a lot of intervalIDs to deal with.
1000 - 1 秒
每隔一秒,它就会提醒“negawebblog.wordpress.com”
1000 - 1 secs.
Every one second, it will alert 'negaweblog.wordpress.com'