gpt4 book ai didi

javascript - 理解一个接一个地执行 setTimeout() 函数

转载 作者:行者123 更新时间:2023-12-03 21:03:59 24 4
gpt4 key购买 nike

我需要在固定的时间间隔内一个接一个地执行多个函数,因此使用了setTimeout。我想确保我了解它是如何执行的。我有以下逻辑:

setTimeout(function() {
//Execute first function
}, 200);

setTimeout(function() {
//Execute second function
}, 400);

setTimeout(function() {
//Execute third function
}, 600);

这是否意味着第一个函数在 200 毫秒后执行,第二个在第一个后 200 毫秒执行,第三个在第二个后 200 毫秒等等?或者我需要改变什么。

最佳答案

Does this mean that first function execute after 200ms, second one 200ms after first and third one 200ms after second and so on?

本质上,是的,这就是它的意思。但是请记住 the specification仅保证延迟参数是必须等待的最小时间,并且浏览器有时可以并且确实会限制这些调用 - 特别是如果选项卡未激活:

Note: This API does not guarantee that timers will fire exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

和:

  1. Optionally, wait a further user-agent defined length of time.

Note: This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

此外,如果您的任何函数需要花费大量时间来运行,则一个函数结束与下一个函数开始之间的延迟可能不会是 200 毫秒 - 它可能会更短。

关于javascript - 理解一个接一个地执行 setTimeout() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com