Stop setInterval
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
}
});
}
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>');
}
});
}
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = 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
clearInterval(interval);
}
});
}
You have to assign the returned value of the setInterval
function to a variable
var interval;
$(document).on('ready',function(){
interval = setInterval(updateDiv,3000);
});
and then use clearInterval(interval)
to clear it again.
USE this i hope help you
var interval;
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
/* clearInterval(interval); */
stopinterval(); // stop the interval
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
function playinterval(){
updateDiv();
interval = setInterval(function(){updateDiv();},3000);
return false;
}
function stopinterval(){
clearInterval(interval);
return false;
}
$(document)
.on('ready',playinterval)
.on({click:playinterval},"#playinterval")
.on({click:stopinterval},"#stopinterval");