【问题标题】:Can't stop setInterval with clearInterval无法使用 clearInterval 停止 setInterval
【发布时间】:2021-11-25 14:13:48
【问题描述】:

已经在小提琴中玩了 4 个小时,但找不到解决方案...

HTML:

Real Time Data: <input type="checkbox" id="dataStream"/>

js:

var chartInt = null;
$("#dataStream").change(function() {
    if(this.checked) {
        var chartInt = setInterval(function() { alert('checked') }, 7000);
    } else {
        clearInterval(chartInt);
        chartInt = null;
        alert('unchecked');
    }
});

注意:由于 clearInterval 不起作用,您需要单击 jsfiddle 中的“运行”以使其在单击复选框后停止,因此警报之间有 7 秒...

这里是 jsfiddle 的链接:http://jsfiddle.net/5udtC/5966/

谢谢!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    不要在本地范围内重新定义变量

    var chartInt = null;
    $("#dataStream").change(function() {
        if(this.checked) {
            chartInt = setInterval(function() {  // no "var" here
                alert('checked') 
            }, 7000);
        } else {
            clearInterval(chartInt);
            alert('unchecked');
        }
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多