setTimeout之前的clearInterval不起作用

我有清除间隔的问题。 我有3个函数start3start2start3 。 在这里你只能看到第一个。 函数count1和变量myVar1具有相同的原理,它们的编号相同。 现在问题是clearInterval仅在第一个函数之后工作(请参阅控制台日志)。 在第二次开始后2 start2()任何事情发生在我自己无法解释的地方。 我做了一个演示 。

 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个事件监听器,它们都有效。 这导致了这个问题。

因此,当您调用下一个时,请取消设置事件侦听器。

 $("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使其易于检查它是如何工作的。