我想向用户弹出窗口显示 2 秒,一个接着一个(可以是任何数字,假设 17)。任何想法如何做到这一点?function sleep(miliseconds) { var currentTime = new Date().getTime(); while (currentTime + miliseconds >= new Date().getTime()) { }}/*First option*/ function printFailureMessages (failureMessages){ failureMessages.forEach(message => { document.getElementById("myPopup").innerHTML = message; document.getElementById("myPopup").classList.toggle("show"); sleep(1500); document.getElementById("myPopup").classList.toggle("show"); });}/*Second option*/function printFailureMessages (failureMessages){ failureMessages.forEach(message => { document.getElementById("myPopup").innerHTML = message; document.getElementById("myPopup").classList.toggle("show"); setTimeout(function(){ document.getElementById("myPopup").classList.toggle("show"); },1500); });}当 failureMessages 大小为 1 时效果很好...顺便说一句 - 我尝试了 setTimeOut 的更多变体,但不成功..
1 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
您可以尝试使用async/await这样的方法:
// Return a promise that resolves after "miliseconds" milliseconds
function sleep(miliseconds) {
return new Promise(res => setTimeout(res, miliseconds));
}
// Make this function async function
async function printFailureMessages(failureMessages) {
for (var i = 0; i < failureMessages.length; i++) {
document.getElementById("myPopup").innerHTML = failureMessages[i];
document.getElementById("myPopup").classList.toggle("show");
await sleep(1500); // wait for this promise to finish
document.getElementById("myPopup").classList.toggle("show");
}
}
printFailureMessages(['Hello', 'World']);
- 1 回答
- 0 关注
- 61 浏览
添加回答
举报
0/150
提交
取消