正确使用setTimeout

时间:2018-06-24 23:54:59

标签: javascript settimeout

我正在尝试使它成为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

3 个答案:

答案 0 :(得分:3)

两个问题:

  • 调用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);
}

答案 1 :(得分:1)

setTimeout是异步的,它不会暂停执行。

var count = 10;
var delay = function(){
  if (count > 0) {
    count--;
    document.write(count);
    setTimeout(delay, 1000); // check again in a second
  }
}
delay();

这可能有效,但是在页面加载完成后,我认为document.write不起作用。这意味着您无法在超时回调中调用它。

答案 2 :(得分:1)

下面是使用searchterms = ['cheese', 'hippos', 'whales', 'beluga'] async def sendQueries(queries, deposit=list()): with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: loop = asyncio.get_event_loop() futures = [ loop.run_in_executor( executor, searching(queries) ) ] for response in await asyncio.gather(*futures): deposit.append(response.json()) return deposit def running(): loop = asyncio.get_event_loop() loop.run_until_complete(loop.create_task(sendQueries(searchterms))) loop.close() print(running()) print(str(time.time() - x)) setInterval的示例

console.log