我正在为我已经开发的应用程序添加新功能。我正在尝试添加自动渲染功能,该功能会在一定时间间隔后自动渲染屏幕的某些部分。我正在使用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)”。
但是,还有其他办法吗?
希望我已经把所有内容都放在一边,以便人们可以理解我的问题。
提前致谢
答案 0 :(得分:1)
您的评论是正确的 - 您必须将clearInterval(IntervalId)放入停止事件所需的所有事件中。这样做有问题吗?
编辑:
用课堂识别它们 - 比如榆树。完成后,使用$(“。elm”)。单击(clearinterval)。
答案 1 :(得分:1)
另一种方法是做类似的事情:
$(".myBtn").click(function(){
setTimeout(someFunction,2000);
});
var someFunction = function()
{
// CODE HERE
if(conditions for stopping function are not met){
//Run function again
setTimeout(someFunction, 2000);
}
}
虽然代码更多,但我发现管理起来更容易,特别是如果你最终需要处理很多的intervalID。
答案 2 :(得分:-2)
setInterval("alert('negaweblog.wordpress.com')",1000);
1000 - 1秒。
每隔一秒,它会提醒'negaweblog.wordpress.com'