Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel Javascript timeout

Tags:

javascript

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

like image 898
BuZz Avatar asked Jun 21 '26 18:06

BuZz


2 Answers

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.

like image 195
Michael Robinson Avatar answered Jun 24 '26 07:06

Michael Robinson


To clear a setTimeout, use clearTimeout.

like image 40
kojiro Avatar answered Jun 24 '26 07:06

kojiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!