猿问

弹出窗口 - 一个接一个

我想向用户弹出窗口显示 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 的更多变体,但不成功..


慕田峪7331174
浏览 62回答 1
1回答

饮歌长啸

您可以尝试使用async/await这样的方法:// Return a promise that resolves after "miliseconds" millisecondsfunction sleep(miliseconds) {&nbsp; &nbsp;return new Promise(res => setTimeout(res, miliseconds));}// Make this function async functionasync function printFailureMessages(failureMessages) {&nbsp; &nbsp;for (var i = 0; i < failureMessages.length; i++) {&nbsp; &nbsp; &nbsp; document.getElementById("myPopup").innerHTML = failureMessages[i];&nbsp; &nbsp; &nbsp; document.getElementById("myPopup").classList.toggle("show");&nbsp; &nbsp; &nbsp; await sleep(1500); // wait for this promise to finish&nbsp; &nbsp; &nbsp; document.getElementById("myPopup").classList.toggle("show");&nbsp; &nbsp;}}printFailureMessages(['Hello', 'World']);
随时随地看视频慕课网APP

相关分类

Html5
我要回答