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

How to fire different setInterval functions at different moments of time?

假设我有

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

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

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

有没有办法检查第一个 boo 间隔什么时候开始,并确保 bla 发生,不是同时发生,而是在 2500 毫秒后发生boo?

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

不能。 JavaScript 在领域内运行单个线程(松散地,page/tab)。该线程从头到尾一次只做一件事。因此,即使这些计时器在同一微秒内触发,执行这些回调的作业也会进入同一队列,并且线程一次处理一个。

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

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);

在set timeout中调用bla的设置间隔,提供时间为2500,

let boo = setInterval(() => console.log('boo'), 5000);
setTimeout(()=>{
 let bla = setInterval(() => console.log('bla'), 5000);
 }, 2500);