setTimeout 之前的 clearInterval 不起作用

clearInterval before setTimeout wont work

我在清除间隔时遇到问题。我有 3 个函数 start1start2start3。在这里你只能看到第一个。函数 count1 和变量 myVar1 具有相同的原理,它们具有相同的编号。现在的问题是 clearInterval 仅在第一个函数之后有效(参见控制台日志)。在第二个 start2() 之后,发生了我自己无法解释的任何事情。我做了一个 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 个事件监听器并且它们都有效。这导致了问题。

所以当你调用下一个时取消设置事件监听器。

$("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 以便于检查其工作原理。