首页 > 解决方案 > 如何修复:forEach 函数中的 setTimeout 函数未遵循正确的超时

问题描述

我正在尝试在我的网站上显示消息,每条消息每 3 秒后显示一次。我通过带有 forEach 函数的数组(包含消息)将它们放入 setTimeout 函数中,但它只在 3 秒后显示最后一条消息,而不是在 3 秒后显示所有消息。

我尝试调试,这里奇怪的部分是它确实在调试中工作,只是没有它。

const travelIntro = $text => {
  const arrMessages = ['You are travelling through empty space...', 'You wake up with only 5% oxygen left barely breathing', 'All of the sudden your ship starts up'];
  arrMessages.forEach(message => {
    setTimeout(function () {
      $text.innerHTML = message;
    }, 3000);
  });
}

所以我希望它在 3 秒后在每条消息之间切换,而不仅仅是显示数组中的最后一条。

标签: javascripthtml

解决方案


我认为您正在寻找setInterval,然后在它返回未定义时清除它。在这里小提琴:https ://jsfiddle.net/xukL1w0a/

const arrMessages = ['You are travelling through empty space...', 'You wake up with only 5% oxygen left barely breathing', 'All of the sudden your ship starts up'];

let messages = setInterval(function () {
  message = arrMessages.shift();
    if (message === undefined) {
     clearInterval(messages);
     return;
  }
  console.log(message)
},3000);

推荐阅读