停止setInterval [英] Stop setInterval

查看:132
本文介绍了停止setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在错误处理程序中反复运行,停止此间隔。这是可能的,如果是的话,如何?

I want to stop this interval in the error handler from running repeatedly. Is that possible, and if so, how?

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


推荐答案

您需要设置返回值的 setInterval 添加到click处理程序范围内的变量中,然后使用 clearInterval()像这样:

You need to set the return value of setInterval to a variable within the scope of the click handler, then use clearInterval() like this:

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

这篇关于停止setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆