views:

134

answers:

2

I have a piece of Javascript that checks for a condition (via an AJAX call) every n seconds. If that condition is true, it stops checking. I have implemented it in the following way:

var stopTimer;
var timerId = setInterval(function() {

    /* Make Ajax Calls and set stopTimer */

    if (stopTimer) {
        clearInterval(timerId);
    }
}, 10000);

However, I find erratic behaviour: Works sometimes, but at other times, it keeps checking forever. I have checked that (as much as is possible) there is no error in any part of the code.

I am therefore suspecting that calling clearInterval inside a setInterval handler might be the culprit. Is that right? Is it OK to call clearInterval inside a setInterval handler?

Thank you for your attention

+1  A: 

It's safe. The issue is probably to do with stopTimer not being set as you expect.

SpliFF
Thanks. Will check and share findings
Gurunandan
+1  A: 

I don't think there will be any issue with your code unless the AJAX function is erroneous. You have to take care of the success and error callbacks of the AJAX function so that there won't be any issue with the loop not being stopped.

Also I think you are constantly polling the server for a response and then doing the appropriate action. You can use Reverse AJAX to do this kind of process.

rahul
Thanks. Yes it is possible that the round-time for the Ajax to complete might interfere with the repeat interval set by setInterval. Will look into this and share findings
Gurunandan