倒计时并更改变量

Count down and change variable as it happens

我是运行一个for循环,每次迭代之间有1秒的中断:

<html>
<body>
<script>

var text = "";
var i;

// Wait function
function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
  wait(100)
}

</script>

<script>document.write(text)</script>

</body>

目前,当我在网络浏览器中打开文件时,浏览器 window 一直在加载,直到 for 循环完成,然后显示结果(五行输出)。有没有办法显示输出 "as it happens"。我的意思是,我打开页面,每秒打印一行。 谢谢!

您应该在 Javascript 中了解超时和间隔概念。

这是完成工作的代码。检查一下。

<html>
<body>
<script>

function waitAndWrite(num) {
    setTimeout(() => {
        let text = "The number is " + num + "<br>";
        document.write(text)
    }, num * 1000)
}

for (let i = 0; i < 5; i++) {
    waitAndWrite(i)
}
</script>
</body>

你想手动实现的,你可以用 WindowOrWorkerGlobalScope.setTimeout():

The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.

for (let i = 0; i < 5; i++) {
  setTimeout(() => document.write("The number is " + i + "<br>"), 1000 * i); // multiply the delay with i in each iteration
}

您可以使用 setInterval(fn, timeout) src 而不是您自己的 "wait" 函数。

var i = 0;
var interval = setInterval(() => {
  i = i + 1;
  if(i === 5) {
    clearInterval(interval);
  }
  document.write("Your text " + i);
}, 1000);