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.

其他提示

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:

The setTimeout() method must return the value returned by the timer initialization steps, passing them the method's arguments... and the repeat flag set to false.

The setInterval() method must return the value returned by the timer initialization steps, passing them the method's arguments.... and the repeat flag set to true.

2) This single function - the "timer initialization steps" mentioned above - uses a single list of timers:

2, ...let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

10, Return handle...

3) clearTimeout() and clearInterval() both operate on that list (and in fact are not differentiated by the spec in any way)

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method, if any. (If handle does not identify an entry in the list of active timers of the WindowTimers object on which the method was invoked, the method does nothing.)

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:

It's worth noting that the pool of IDs used by setTimeout() and setInterval() are shared, which means you can technically use clearTimeout() and clearInterval() interchangeably. However, for clarity, you should avoid doing so.

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? :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top