the murmurous sea

Reasons for setTimeout()/setInterval() delays longer than specified 본문

#dev/개념정리

Reasons for setTimeout()/setInterval() delays longer than specified

lunacer 2020. 7. 1. 14:22

1. Timeouts throttled to ≥ 4ms

   : In modern browsers, setTimeout()/setInterval() calls are throttled to a minimum of once every 4 ms when successive calls are triggered due to callback nesting (where the nesting level is at least a certain depth), or after a certain number of successive intervals. 

   : In Chrome and Firefox, the 5th successive callback call is clamped; Safari clamps on the 6th call; in Edge its the 3rd one. Gecko started to treat setInterval() like this in version 56 (it already did this with setTimeout(); see below).

 

Historically some browsers implemented this throttling behaviour a bit differently (e.g. Firefox) — on setInterval() calls made from anywhere, or when a nested setTimeout() is called where the nesting level is at least a certain depth.

To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here.

 

2. Timeouts in inactive tabs throttled to ≥ 1000ms

   : To reduce the load (and associated battery usage) from background tabs, timeouts are throttled to firing no more often than once per second (1,000 ms) in inactive tabs. 

 

3. Throttling of tracking timeout scripts

   : Since Firefox 55, tracking scripts (e.g. Google Analytics, any script URL that Firefox recognises as a tracking script through its TP lists) have been subject to further throttling. When running in the foreground, the throttling minimum delay is still 4ms. In background tabs, however, the throttling minimum delay is 10,000 ms, or 10 seconds, which comes into effect 30 seconds after a document has first loaded.

The prefs that control this behaviour are:

dom.min_tracking_timeout_value: 4
dom.min_tracking_background_timeout_value: 10000
dom.timeout.tracking_throttling_delay: 30000

 

4. Late timeouts

  : In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks. One important case to note is that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated.

(function loop(){
   setTimeout(function() {
      // Your logic here

      loop();
  }, delay);
})();

Will write to the console:

After setTimeout
foo has been called

This is because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected.

'#dev > 개념정리' 카테고리의 다른 글

DOM Events: mouseover/out & mouseenter/leave  (0) 2020.07.28
DOMContentLoaded vs. load  (0) 2020.07.06
setTimeout vs. setInterval  (0) 2020.06.30
json.parse() vs. response.json  (0) 2020.06.25
JS: match() vs includes()  (0) 2020.06.24
Comments