Nấm Lùn
Nấm Lùn

Reputation: 1275

Stop executing function in setInterval

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!

Upvotes: 1

Views: 5734

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

Try:

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


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

}

Upvotes: 1

Alnitak
Alnitak

Reputation: 339947

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.

Upvotes: 6

Related Questions