小编典典

停止setInterval

javascript

我想停止error处理程序中的此间隔重复运行。那有可能吗?

// example code
$(document).on('ready',function(){
    setInterval(updateDiv,3000);
});

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
            // I want to stop it here
        }
    });
}

阅读 408

收藏
2020-05-01

共1个答案

小编典典

您需要setInterval在点击处理程序范围内将的返回值设置为变量,然后clearInterval()像这样使用:

var interval = null;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});

function updateDiv(){
    $.ajax({
        url: 'getContent.php',
        success: function(data){
            $('.square').html(data);
        },
        error: function(){
            clearInterval(interval); // stop the interval
            $.playSound('oneday.wav');
            $('.square').html('<span style="color:red">Connection problems</span>');
        }
    });
}
2020-05-01