When using setTimeout do you have to clearTimeout?
JavascriptJavascript Problem Overview
Someone told me that when you use setTimeout
you must clear it with clearTimeout
. I can understand before the timeout runs out, but why after? Or is it untrue?
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
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.
Solution 3 - Javascript
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.
Solution 4 - Javascript
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.
Solution 5 - Javascript
No reason to clear it after it's completed. Your friend might have been confused with setInterval
.