Jump to content

Ajax / Stop Perpetual setInterval


MoFish

Recommended Posts

Hello,

 

I have some ajax code to get the some progress indications from a json file. Everything is working well, however the setInterval never ends.

 

I was hoping that once the $.post success event had been fired that it would of stop the setInterval part by setting varLoading to false.

$.post('work.php', function(data){
	alert("finished");
	varLoading = false;
});

if(varLoading) {
	setInterval(function() {
	    $.getJSON('progress.json', function(data) {
	    	progress(data.progress, data.message);
	    });
	}, 2000);
}

I then tried adding it into a function, and calling that based on the status of the varLoading variable being true or false. However this seems to increment alot quicker than 2 seconds and caused by browser to crash. I think this is also going on into 'infinity and beyond' ::)

$.post('work.php', function(data){
    alert("finished");
    varLoading = false;
});

if(varLoading){
    checkStatus();
}

function checkStatus() {
    if(varLoading) {
        setInterval(function() {
            $.getJSON('progress.json', function(data) {
                progress(data.progress, data.message);
            });
            checkStatus();
        }, 2000);
    }
}

Could anyone help point me in the right direction?

 

Thanks

 

MoFish

Link to comment
https://forums.phpfreaks.com/topic/286629-ajax-stop-perpetual-setinterval/
Share on other sites

To stop the interval you need to save the return value of setInterval then call clearInterval when you want to stop it.

 

var intervalId = setInterval(function(){
   ...
}, 2000);

$.post('work.php', function(){
   clearInterval(intervalId);
   ...
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.