gpt4 book ai didi

javascript - 如何在不同时刻触发不同的 setInterval 函数?

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

假设我有

let boo = setInterval(() => console.log('boo'), 5000);

假设我想添加另一个间隔函数,但我想确保它不会同时启动:

let bla = setInterval(() => console.log('bla'), 5000);

有没有办法检查第一个 boo 间隔何时触发,并确保 bla 发生,而不是同时发生,但是,比如说,boo 后 2500 毫秒?

最佳答案

but I want to make sure it doesn't fire up at the same time

不能。 JavaScript 在领域(宽松地说,页面/选项卡)内运行单个线程。该线程从开始到结束一次只做一件事。因此,即使这些计时器在同一微秒触发,执行这些回调的作业也会进入同一个队列,并且线程一次处理一个。

如果计时器回调正在完成的工作启动异步进程,则第二个计时器调用可以在计时器回调启动(并返回)之后但异步工作正在完成时进入。如果您想防止这种情况发生,则必须在两者之间进行一些手动同步。

Is there a way to check when is the first boo interval going to fire out and to make sure that bla happens, not at the same time, but, say, 2500 ms after the boo?

我可能会使用单个计时器来做到这一点:

let flag = true;
setInterval(() => {
if (flag) {
console.log("boo");
} else {
console.log("bla");
}
flag = !flag;
}, 2500);

关于javascript - 如何在不同时刻触发不同的 setInterval 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60759952/

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