Jump to content


Photo

Ajax / Stop Perpetual setInterval


Best Answer kicken, 01 March 2014 - 03:25 PM

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);
   ...
});
Go to the full post


  • Please log in to reply
1 reply to this topic

#1 MoFish

MoFish

    Advanced Member

  • Members
  • PipPipPip
  • 148 posts

Posted 01 March 2014 - 05:12 AM

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



#2 kicken

kicken

    Wiser? Not exactly.

  • Gurus
  • 2,714 posts
  • LocationBonita, FL

Posted 01 March 2014 - 03:25 PM   Best Answer

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

Recycle your old CD's, don't trash them!
Did I help you out?  Feeling generous? I accept tips via Paypal or Bitcoin @ 14mDxaob8Jgdg52scDbvf3uaeR61tB2yC7




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com