javascript 使用 setTimeout 时必须要 clearTimeout 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7391567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:57:38  来源:igfitidea点击:

When using setTimeout do you have to clearTimeout?

javascript

提问by NebulaFox

Someone told me that when you use setTimeoutyou must clear it with clearTimeout. I can understand before the timeout runs out, but why after? Or is it untrue?

有人告诉我,使用setTimeout时必须用clearTimeout. 在超时用完之前我可以理解,但为什么之后呢?或者它是不真实的?

采纳答案by jmar777

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.

如果句柄未标识在其上调用 [clearTimeout] 的 WindowOrWorkerGlobalScope 对象的活动计时器列表中的条目,则该方法不执行任何操作。

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

换句话说,这是一个空操作;什么都不会发生,也不会抛出错误。

回答by Madara's Ghost

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.

您实际上并不需要使用clearTimeout,只有在您希望取消已在超时之前设置的超时时才使用它。

It's usually more practical to use clearIntervalwith setIntervalbecause setIntervalusually runs indefinitely.

它通常更实用clearIntervalsetInterval因为setInterval通常可以无限期运行。

回答by g.d.d.c

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

clearTimeout仅用于取消超时。超时触发后,可以安全地将其单独放置。 clearInterval通常更需要防止它无限期地持续下去。

回答by Trevor

No, setTimeoutstops running after 1 call. In order to stop setIntervalhowever, you must use clearInterval. If you create an endless loop of setTimeoutthen clearTimeoutcould be used.

不,setTimeout在 1 次呼叫后停止运行。setInterval但是,为了停止,您必须使用clearInterval. 如果您创建一个无限循环setTimeoutthenclearTimeout可以使用。

回答by Blazemonger

No reason to clear it after it's completed. Your friend might have been confused with setInterval.

完成后没有理由清除它。你的朋友可能已经混淆了setInterval