HTML循环中的等待时间

时间:2018-11-23 19:19:18

标签: javascript html

我如何确定两次循环之间的等待时间为10秒?

对吗?

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
       <title>Tableau Zika</title>
    </head>
        <body>
            <script>
var i=3;

do { 

window.open("TESTE" + i + ".HTML","_self");
i++;

setTimeout(alert("4 seconds"),4000);

}
while (i<=5);

</script>

</html>

2 个答案:

答案 0 :(得分:1)

完全不使用循环。只需将您的计时器设置为定期调用回调函数即可。

var counter = 0;

function doWork(){
  if(counter < 5){
    console.log("doing work", counter);
    counter++;
  } else {
    clearInterval(timer);
    console.log("work completed");
  }
}

let timer = setInterval(doWork, 3000);

您还可以通过更改代码以进行递归setTimeout调用来控制计时,以使计时器直到主要工作完成后才开始计时:

var counter = 0;
var timer = null;

(function doWork(){
  // Guard against doWork being called from multiple sources
  // and potentially initiating multiple timers.
  clearTimeout(timer);
  
  if(counter < 5){
    console.log("doing work", counter);
    counter++;
    timer = setTimeout(doWork, 3000);
  } else {
    clearTimeout(timer);
    console.log("work completed");
  }
})();

答案 1 :(得分:1)

您可以使async / await函数在循环期间暂停。这将需要一个现代的javascript引擎,并且需要将逻辑放在一个函数中,然后调用该函数。

const pause = (time) => new Promise(resolve => setTimeout(resolve, time))

async function start(){
    var i=3;

    do { 
      console.log("TESTE" + i + ".HTML")
      i++;
      await pause(1000) // change to 10000 for 10 seconds
    } while (i<=5);
}

start()