When using setTimeout do you have to clearTimeout?
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?
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.
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.
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.
No reason to clear it after it's completed. Your friend might have been confused with setInterval
.
It is always best practice to cleartimeout
after using setTimeout.
let's take a scenario you are using setTimeout
on /abc
page. and you set a time of 10s. and now you move to /something
page before the timeout is completed(less than 10s). but setTimeout
is still running so now you are on /something
page and timeout ends the time and the callback function will run on /something
page in the callback function, you might be using a window object which may affect your /something
page and result in an error or unexpected result.
conclusion- always use cleartimeout
to remove unexpected errors.
Please add your thoughts if I am wrong
精彩评论