Joe Riggs
Joe Riggs

Reputation: 1324

Stop Function From executing after condition is met

My html page fires off 2 php scripts, one to perform a task and another to poll a log file and show results on the html page. After the 'updatestock.php' has finished how do I stop the getStatus() process?

  <script type="text/javascript">
    $(function() {
        startProcess();
        getStatus();

    });

    function startProcess() {

      $("#done").load('updatestock.php');

    }

    function getStatus() {

      $("#status").load('getstatus.php');
        setTimeout("getStatus()",2000);

    }

    </script>

Upvotes: 0

Views: 2147

Answers (4)

ShankarSangoli
ShankarSangoli

Reputation: 69905

var stopProcess = false;


function startProcess() {

    $("#done").load('updatestock.php', function() {

        stopProcess  = true;

    });

}

function getStatus() {

    if ( stopProcess){
        return false;
    }

    $("#status").load('getstatus.php');
    setTimeout("getStatus()",2000);

}

Upvotes: 0

cwallenpoole
cwallenpoole

Reputation: 81988

You'd use clearTimeout:

// persistent variable needed
var timeout = 0;
$(function() {
    startProcess();
    getStatus();

});

function startProcess() {
  // second parameter of load = completion callback
  $("#done").load('updatestock.php',function()
  { 
      // clearTimeout will stop the next getStatus from firing.
      clearTimeout(timeout); 
      timeout = -1;
  });

}

function getStatus() {
  // just in case. You never know what's cached.
  // (the ids for setTimeout are positive).
  if( timeout < 0 ) return; 
  $("#status").load('getstatus.php');
  // sets the ID of the current timeout.
  timeout = setTimeout("getStatus()",2000);

}

Upvotes: 3

Seth
Seth

Reputation: 6260

Use the callback from the load() method to set a flag and then check for it in your getStatus() method:

$(function() {
    startProcess();
    getStatus();

    var flag = false;
});

function startProcess() {

    $("#done").load('updatestock.php', function() {

        flag = true;

    });

}

function getStatus() {

    if ( flag ) return false;

    $("#status").load('getstatus.php');
    setTimeout("getStatus()",2000);

}

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239220

Put the delayed call to getStatus in the callback for load, and use an if statement that determines whether to call it or not based on what getstatus.php returns. It could be a certain response code or bit of data, e.g. "finished": true in a JSON response.

Upvotes: 0

Related Questions