setTimeout 冲过 switch 语句
所以我有以下代码:
let eventSequence = ['EVENT1', 'EVENT2', 'EVENT3'];
const simulateGame = () => {
let timer;
if(!gameStarted) {
clearTimeout(timer);
return;
}
if(eventSequence.length > 0) {
trackEvents(eventSequence[0]);
eventSequence.shift();
} else {
console.log('The End')
dispatch(endGame);
}
timer = setTimeout(simulateGame, 3000);
}
const trackEvents = (eventCode) => {
switch (eventCode) {
case 'EVENT1':
dispatch(EVENT1(payload));
break;
case 'EVENT2':
dispatch(EVENT2(payload));
break;
case 'EVENT3':
dispatch(EVENT3(payload));
break;
default:
return;
}
}
useEffect(() => {
simulateGame();
}, [gameStarted, simulateGame]);
如果我在没有 trackEvents 函数的情况下运行simulateGame,并将其替换为 console.log,则它的行为符合预期,每 3 秒将索引 0 处的事件记录到控制台,然后从数组中删除,直到没有剩余事件。然而,当我放入 trackEvents 函数时,它会快速执行相同的过程,而不考虑 setTimeout 的延迟。对于实现类似事件循环的任何澄清或任何更好的建议,我们将不胜感激。干杯!
So I have the following code:
let eventSequence = ['EVENT1', 'EVENT2', 'EVENT3'];
const simulateGame = () => {
let timer;
if(!gameStarted) {
clearTimeout(timer);
return;
}
if(eventSequence.length > 0) {
trackEvents(eventSequence[0]);
eventSequence.shift();
} else {
console.log('The End')
dispatch(endGame);
}
timer = setTimeout(simulateGame, 3000);
}
const trackEvents = (eventCode) => {
switch (eventCode) {
case 'EVENT1':
dispatch(EVENT1(payload));
break;
case 'EVENT2':
dispatch(EVENT2(payload));
break;
case 'EVENT3':
dispatch(EVENT3(payload));
break;
default:
return;
}
}
useEffect(() => {
simulateGame();
}, [gameStarted, simulateGame]);
If I run the simulateGame without the trackEvents function and replaced it with a console.log, it behaves as expected where every 3 seconds the event at index 0 is logged to the console and then removed from the array until there are no events left. However when I throw in the trackEvents function, It rushes through the same process without any regards to the delay on the setTimeout. Would appreciate any clarification or any better suggestions for implementing a similar sort of event loop. Cheers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论