admin管理员组文章数量:1133919
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?
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?
6 Answers
Reset to default 148It'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
本文标签: javascriptWhen using setTimeout do you have to clearTimeoutStack Overflow
版权声明:本文标题:javascript - When using setTimeout do you have to clearTimeout? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736791743a1953117.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论