我正在尝试使它成为document.write()9,然后暂停1秒,写8,然后暂停1秒,写7,然后暂停1秒,依此类推,直到它达到0。现在,它只是一次打印出整个内容。我究竟做错了什么?

var delay = function(){
setTimeout(delay, 1000); // check again in a second
}

var count = 10;
while (count > 0) {
count--;
delay();
document.write(count);
}


9876543210

最佳答案

两个问题:


调用setTimeout仅使超时后过期的函数排队等待执行-不会暂停主线程。
document.write是document.wrong,通常-如果文档已经被解析,它将被新的HTML字符串替换。请改用适当的DOM方法。


您可以await每秒钟承诺并追加span



const delay = () => new Promise(res => setTimeout(res, 1000));
(async () => {
  let count = 10;
  while (count > 0) {
    await delay();
    count--;
    document.body.appendChild(document.createElement('span')).textContent = count;
  }
})();





您还可以(同步)为每次迭代设置超时:



for (let count = 9; count >= 0; count--) {
  setTimeout(() => {
    document.body.appendChild(document.createElement('span')).textContent = count;
  }, (10 - count) * 1000);
}

关于javascript - 正确使用setTimeout,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51014855/

10-12 01:25
查看更多