简体   繁体   English

javascript setTimeout需要执行多次时间可能是什么原因?

[英]What could be the reason for a javascript setTimeout taking multiple times as long to execute?

what could be the reason for a setTimeout to wait 2-4 times as long as configured to be executed? setTimeout等待2-4次(配置为执行)的原因是什么?

  var TIMEOUT  = 700;

  console.log("TIMEOUT", TIMEOUT);

  var preTimeout = new Date();
  setTimeout(function() {
    console.log("timeout took:", new Date() - preTimeout);
  }, TIMEOUT);

This results in timeout took: from 1200-4000 on a website. 这导致timeout took:网站上的1200-4000。

setTimeout() doesn't mean execute the code after exactly N milliseconds. setTimeout()并不意味着在精确的 N毫秒后执行代码。 It rather means, don't execute the code for at least N milliseconds. 而是意味着, 至少在 N毫秒内不要执行代码。

The asynchronous code such as the setTimeout() callback is put on an event loop queue until all syncrhonous code finishes executing, and then it's run. 诸如setTimeout()回调之类的异步代码被放在事件循环队列中,直到所有同步代码完成执行,然后运行。 This includes any async code that gets run in the queue before the timeout period. 这包括在超时时间之前在队列中运行的所有异步代码。 Your callback can run only after all those are done. 只有完成所有这些操作后,您的回调才能运行。

Here's a small demo to show this using synchronous while loop: 这是一个小示例,使用同步while循环来演示:

https://jsfiddle.net/foxbunny/1a9rckdq/ https://jsfiddle.net/foxbunny/1a9rckdq/

Code like the one in the demo is what you'll hear people referring to as 'blocking'. 像演示中的代码一样,您会听到人们所说的“阻塞”。 This is because it blocks the event loop queue. 这是因为它阻止了事件循环队列。

I've also written a somewhat long article on the topic if you want a throrough overview . 如果您需要详尽的概述,我也就该主题写了一篇较长的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM