javascript - 如何修复: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 秒后在每条消息之间切换,而不仅仅是显示数组中的最后一条。
解决方案
我认为您正在寻找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);
推荐阅读
- python - 在 Python for 循环中运行迭代命令
- java - 在循环中将多个复选框值发送到 servlet
- css - font-face 不适用于汇总配置 - 组件库
- dataweave - Mule 4:如何从数组生成文本文件
- flutter - Flutter中Overscroll指示器的不同颜色?
- python - 如何确定某些列之和为0的行的索引?
- kubernetes - 如何使用 Kubernetes 资源的动态输出作为 Pod 中的环境变量?
- cookies - 如何修复错误与 http://google.com/ 上的跨站点资源关联的 cookie 设置为没有 `SameSite
- c# - AWS Neptune Gremlin C# GraphTraversalSource 不工作
- r - 需要一个功能来导入极其混乱的 txt 文件