klamertd klamertd - 7 months ago 17
Javascript Question

clearInterval before setTimeout wont work

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);
}


console log:

5 start1

6 start2

start3

start2

start3

start2

Answer

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);
        }
    }
});

The code above uses >=5 instead of your original code $('#number').text() == 5 to make it easily checkable how it works.