www.webdeveloper.com
Results 1 to 2 of 2

Thread: Ajax / Stop setInterval Once Success

  1. #1
    Join Date
    Nov 2006
    Posts
    9

    Question Ajax / Stop setInterval Once Success

    Hello,

    I have a problem and hoped someone could help me. I created a thread in another forum, but was advised it should have been in this section (http://www.webdeveloper.com/forum/sh...l-Once-Success) so here goes again.

    --

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

    I'm looking for some advise on the best way to stop the setInterval bit of code, once the $.post success event has been fired (alert finished).

    At the moment it continually refreshes the page even once I have had the "finished" alert.

    Code:
    $.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 made this into a function, which i hoped would help the looping problem based on the status of the varLoading variable being true or false.

    This seems to have made things worse, and increments alot quicker than 2 seconds each time, eventually causing the browser to crash. I think this is also going into 'infinity and beyond'

    Could anyone help point me in the right direction?

    In summary I want to stop the setInterval bit of code once the $post request has finished.

    Thanks,

    h4x0rz3d

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

  2. #2
    Join Date
    Mar 2012
    Posts
    1,643
    Have you tried setTimeout() instead of setInterval()?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles