Assume that I have some files : server.php, client.php and one table : user[id, name, status]
server.php will handle somethings like : update user status, etc…
In client.php I have an ajax call to server.php for checking if the status is activated (in every 10 seconds):
$(document).ready(function(){
setInterval(function(){
check_user_status(user_id)
},10000);
});
check_user_status = function (user_id) {
$.ajax({
type: "post",
data: "user_id="+user_id,
url : "server.php",
success: function(data){
// do something with the response
// I want to exit the checking operation if user is already activated
},
error: function(e){
alert("Error occurred");
}
});
}
How could it be done?
Thanks for your time!
Remember the ID that has been given to your timer:
and then cancel it when conditions are met:
The
timervariable will need to be in “scope” – the simplest solution is to put all of your code inside thedocument.readyhandler.FWIW, it’s actually better to use
setTimeoutinstead ofsetInterval, and then re-start the timer each time around.setIntervalwill cause problems if your server goes unresponsive because it’ll dutifully keep queueing callbacks every 10 seconds. Once the server responds it’ll suddenly try to run all those callbacks straight away.Using
setTimeoutinstead will ensure that no new check gets queued until the previous one has actually completed.