BuZz
BuZz

Reputation: 17485

Cancel Javascript timeout

I have a long process hosted on a Web Server. The thing is triggered from a Web Page, at the click of a button by a user. Some Javascript polls regularly via Ajax to check if the operation has completed server side. To do this, I use setInterval, and later on clearInterval to stop polling.

If this takes too long (e.g. server has crashed), I'd like the client to be informed by some sort of timeout. I've done some research and found about setTimeout. Problem is, if the operation finishes successfully before the timeout, I'd like to cancel this one.

  1. How to do this ?
  2. Would you suggest a different approach ?

PS : I'm targetting IE7/IE8 in particular, but always open to some JQuery

Upvotes: 2

Views: 2115

Answers (3)

Stephen P
Stephen P

Reputation: 14810

You want two timers (as you said)

  1. repeating interval to do the next poll and
  2. one-time expiration to give up if the server never responds

If the polling is successful you want to clear both the polling interval and cancel the failure timer. If the expiration timer fires you want to clear the polling interval

var checkCount = 0;
function checkComplete() {
    console.log("test " + checkCount);
    if (checkCount++ > 10) {
        console.log("clearing timeout");
        window.clearInterval(pollInterval);
        window.clearTimeout(expireTimer);
    }
}
function cancelPolling(timer) {
    console.log("clearing poll interval");
    window.clearInterval(pollInterval);
}
var pollInterval = window.setInterval(checkComplete, 500);
var expireTimer = window.setTimeout(cancelPolling, 10000);

You can fiddle with the checkCount constant "10" - keep it low to simulate polling success, raise it higher for the timeout to occur before the checkCount is reached, simulating polling failure.

Upvotes: 0

Michael Robinson
Michael Robinson

Reputation: 29498

As long as you store your interval's id in a variable, you can use it to clear the interval at any time.

var interval = window.setInterval(yourFunction, 10000);

...elsewhere...

window.clearTimeout(interval);

For more information see the Mozilla Documentation's setInterval example.

Put together a quick JS Fiddle containing a modified version of Mozilla's Example.

Upvotes: 9

kojiro
kojiro

Reputation: 77137

To clear a setTimeout, use clearTimeout.

Upvotes: 4

Related Questions