在控制台中输入此内容,请参阅:
tick = () => console.log(1);
tock = () => console.log(2);
tickID = setInterval(
() => this.tick(),
2000
);
console.log(tickID);
tockID = setTimeout(
console.log(
setInterval(
() => this.tock(),
2000)
),
1000
);

我包含了setInterval的两个console.logs,表明它们没有相同的ID。
我想要一个时钟交替tick()和tock()每1000ms。
(请不要回答我在哪里使用布尔值,我不想要那个,我想知道为什么这个逻辑不起作用)
答案 0 :(得分:3)
您需要回复setTimeout
:
tick = () => console.log(1);
tock = () => console.log(2);
tickID = setInterval(() => tick(), 2000);
console.log(tickID);
tockID = setTimeout(() => setInterval(() => tock(), 2000), 1000);

答案 1 :(得分:0)
你正在立即执行第二个功能......
tockID = setTimeout(
console.log( // <-- this is being executed here, not in 1 second
setInterval(
() => this.tock(),
2000)
),
1000
);
将其更改为此将修复它...
tockID = setTimeout(function() {
console.log(
setInterval(
() => this.tock(),
2000)
);
},
1000
);