My html page fires off 2 php scripts, one to perform a task and another to开发者_JAVA技巧 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>
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);
}
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);
}
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);
}
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.
精彩评论