When working on some Javascript for a web application, I noticed that I had used setTimeout
, but I had tried to clear it with clearInterval
and it stopped the timeout from occurring in Google Chrome and Internet Explorer 9.
Are clearTimeout
and clearInterval
interchangeable?
Here's a JSfiddle with an example of what I'm talking about.
No, they are not interchangeable.
Sure, some browsers may very well share the same code to clear intervals and timeouts the same way, but does not mean they are interchangeable and you are most certainly not guaranteed that they would work the same across all browser implementations. It comes down to these two methods being defined differently for different purposes and therefore you should use them for their designated uses.. Otherwise, you're just asking for trouble.
Even if they can be used synonymously now it could change at any time in the future. Why shouldn't you call a spade a spade? :-)
Actually I believe that we can make a fairly strong conclusion from the W3C spec (http://www.w3.org/TR/html5/webappapis.html#timers). It is not explicitly guaranteed but we have a lot of evidence that almost any reasonable implementation would have this behavior:
1) Timeouts and Intervals actually use the same underlying function:
2) This single function - the "timer initialization steps" mentioned above - uses a single list of timers:
3) clearTimeout() and clearInterval() both operate on that list (and in fact are not differentiated by the spec in any way)
I believe this presents a fairly strong case that clearTimeout and clearInterval should by synonymous according to the spec. This is backed up by the fact that this works in all the browsers I tested (Chrome 37, Firefox 33, and Opera 25).
From the Mozilla reference: