Does Node.js enforce a minimum delay for setTimeout?

前端 未结 3 1300
独厮守ぢ
独厮守ぢ 2020-12-09 01:28

In browsers, if you use setTimeout from within a function called by setTimeout then a minimum delay of 4ms will be enforced. Mozilla\'s developer w

3条回答
  •  庸人自扰
    2020-12-09 01:59

    It doesn't have a minimum delay and this is actually a compatibility issue between browsers and node. Timers are completely unspecified in JavaScript (it's a DOM specification which has no use in Node and isn't even followed by browsers anyway) and node implements them simply due to how fundamental they've been in JavaScript's history and how irreplaceable they are otherwise.

    Node uses libuv which a cross-platform abstraction layer for lower level system things like file-system, networking stuff, etc. One of those things is timers, which Node provides a minimal wrapper around. At the libuv level, the timers used are the system-specific high precision timers. In Windows, for example, this is implemented using QueryPerformanceFrequency and FileTimeToSystemTime which provides resolution measured in nanoseconds.

    In Node, if you specify setTimeout(callback, 1) then it will be executed one millisecond later (assuming the system doesn't delay it due to be overwhelmed). In browsers, the minimum time will be 4 milliseconds as specified by the HTML5 spec: https://developer.mozilla.org/en/DOM/window.setTimeout. This isn't a guaranteed time, just a minimum. Most browsers can be expected to have a ~15ms resolution which impacts DOM animations.

    One valid piece of info is that timeouts set to the same millisecond, during the same frame, will be executed in the order they were queued. If you were to do:

      setTimeout(callback1, 1);
      setTimeout(callback2, 1);
      setTimeout(callback3, 1);
      setTimeout(callback4, 1);
    

    All in one block, Node should call them in that order. This only applies if they have the exact same resolution time.

    http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx

    http://msdn.microsoft.com/en-us/library/windows/desktop/ms724280(v=vs.85).aspx

提交回复
热议问题