Jump to content

Ajax / Stop Perpetual setInterval


MoFish
Go to solution Solved by kicken,

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
Share on other sites

  • Solution

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);
   ...
});
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.