Stop setInterval

Henrik Petterson picture Henrik Petterson · May 8, 2013 · Viewed 217.1k times · Source

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

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

Answer

Rory McCrossan picture Rory McCrossan · May 8, 2013

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