setIntervalを停止する 質問する

setIntervalを停止する 質問する

ハンドラー内のこの間隔が繰り返し実行されるのを停止したいのですが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
        }
    });
}

ベストアンサー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>');
        }
    });
}

おすすめ記事