When using setTimeout do you have to clearTimeout?

No, setTimeout stops running after 1 call. In order to stop setInterval however, you must use clearInterval. If you create an endless loop of setTimeout then clearTimeout could be used.


clearTimeout is only necessary for cancelling a timeout. After the timeout fires, it can safely be left alone. clearInterval is much more typically necessary to prevent it from continuing indefinitely.


It's not true - there's no harm in clearing a timeout after it has finished, but it's not necessary.

Per the specification:

If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which [clearTimeout] was invoked, the method does nothing.

In other words, it's a no-op; nothing happens, and no error will be thrown.


You don't actually need to use clearTimeout, you only use it if you wish to cancel the timeout you already set before it happens.

It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.

Tags:

Javascript