1

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!

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
Nấm Lùn
  • 1,277
  • 6
  • 28
  • 48
  • [clearInterval](https://developer.mozilla.org/en/window.clearInterval) is a good place to start – andyb Jul 17 '12 at 10:32
  • possible duplicate of [how to stop "setInterval"](http://stackoverflow.com/questions/1831152/how-to-stop-setinterval) – andyb Jul 17 '12 at 10:34

2 Answers2

6

Remember the ID that has been given to your timer:

var timer = setInterval( ... );

and then cancel it when conditions are met:

clearInterval(timer);

The timer variable will need to be in "scope" - the simplest solution is to put all of your code inside the document.ready handler.

FWIW, it's actually better to use setTimeout instead of setInterval, and then re-start the timer each time around.

setInterval will 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 setTimeout instead will ensure that no new check gets queued until the previous one has actually completed.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

Try:

var intrvl = setInterval(function(){
        check_user_status(user_id)
    },10000);


....
success: function(data){
 clearInterval(intrvl);

}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162