setTimeout 冲过 switch 语句

发布于 2025-01-11 18:26:46 字数 998 浏览 3 评论 0原文

所以我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文