setTimeout之前的clearInterval无法正常工作 [英] clearInterval before setTimeout wont work
问题描述
我在清除间隔时遇到问题.我有3个功能start1
,start2
,start3
.在这里您只能看到第一个.函数count1
和变量myVar1
具有相同的原理,它们具有相同的编号.现在的问题是clearInterval
仅在第一个功能之后才起作用(请参阅控制台日志).在第二个start2()
之后,发生了任何我自己无法解释的事情.我做了一个演示.
I have a problem with clearing an interval. I have 3 functions start1
, start2
, start3
. Here you can see only the first. The function count1
and variable myVar1
have the same princip they are the same numbered. Now the problem is that clearInterval
only works after the first function (See console log). After the second start2()
anything happens what I cant explain by myself. I made a demo.
start1();
function start1() {
var valuem = 0, dir = 1;
$('#number').text(valuem);
function count1() {
valuem += dir;
$('#number').text(valuem);
if (valuem < 1) dir = 1;
console.log("start1");
}
$("body").on({
'touchstart mousedown': function(e) {
if ($('#number').text() == 5) {
window.clearInterval(myVar1);
window.setTimeout(function() {
start2();
}, 1000);
}
},
'touchend mouseup': function(e) {}
});
var myVar1 = window.setInterval(function() {
count1();
}, 1000);
}
控制台日志:
5 start1
6 start2
start3
start2
start3
start2
推荐答案
第二个函数调用后代码出错的原因是,在调用下一个函数时,您未取消设置mousedown touchstart
事件.
因此,当您运行第二个函数时,您在body
上有2个事件侦听器,并且它们都可以工作.这会导致问题.
The reason your code goes wrong after second function call is You did not unset mousedown touchstart
event when you call next one.
So at the time you run the second function, You have 2 event listener on body
and both of them works. this causes the issue.
因此,当您调用下一个监听器时,请取消设置事件监听器.
So unset the event listener when you call next one.
$("body").on({
'touchstart mousedown': function(e) {
if (parseInt($('#number').text()) >= 5) {
$(e.target).off('touchstart mousedown');
window.clearInterval(myVar1);
window.setTimeout(function() {
start2();
}, 1000);
}
}
});
上面的代码使用>=5
而不是原始代码$('#number').text() == 5
来使其易于检查.
The code above uses >=5
instead of your original code $('#number').text() == 5
to make it easily checkable how it works.
这篇关于setTimeout之前的clearInterval无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!