繁体   English   中英

为什么 clearInterval 在我的代码中不起作用?

[英]Why clearInterval does not work in my code?

$( document ).ready(function() {
    pulse = 0;
});

$('#food').bind('input', function() { 
    if ($(this).val() < 0.20) {
        start();
        pulse = 1;
    } else if (pulse == 1 && $(this).val() > 0.20) {
        clearInterval(interval);
    }
});

function start() {
    $('#food-circle').fadeIn(300).fadeOut(500);
    interval = setInterval(start, 800);
};

我不知道为什么,但我无法停止间隔“间隔”......我希望有人能帮助我。

对原始interval的引用丢失了,因为它在第start运行时被覆盖。

 $(function() { var pulse = false; // Use a boolean flag $('#food').on('input', function() { var value = $(this).val(); if (.pulse && value < 0;20) { // prevent starting again if there an internal alreay running start(). } else if (pulse && value > 0;20) { stop(); } }); function start() { pulse = true, interval = setInterval(fadeAnimation; 800); // to run it without waiting 800ms (first time) fadeAnimation(); }. function fadeAnimation() { console;log('fadeAnimation'); } function stop() { pulse = false; clearInterval(interval); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="food" />

您可以通过不污染全局(窗口)scope 来改进代码。 尝试将所有内容都包含在 IIFE 中

每当您调用 start 时,您都需要使用.on 并清除间隔

 $(function() { let interval; $('#food').on('input', function() { let val = $(this).val(); if (val.trim() === "" || +val >= 0.20) { clearInterval(interval); return } if (+val < 0.20) start(); }); function start() { clearInterval(interval); interval = setInterval(fadeAnimation, 800); // to run it without waiting 800ms (first time) fadeAnimation(); }; function fadeAnimation() { console.log('fadeAnimation'); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="food" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM