Does Node.js enforce a minimum delay for setTimeout?

前端 未结 3 1287
独厮守ぢ
独厮守ぢ 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:54

    From this test, it doesn't seem that it does have a minimum delay.

    If you do a setTimeout() that has a 10ms duration, and long the return value to the console, this is what you get:

     var timer = setTimeout(function(){ console.log(timer);}, 10);
    
     { _idleTimeout: 10,
      _onTimeout: [Function],
      _idlePrev: null,
      _idleNext: null,
      _idleStart: Sun, 28 Aug 2011 14:34:41 GMT } 
    

    Similarly, with a 1ms duration, you get:

     var timer = setTimeout(function(){ console.log(timer);}, 1);
    
     { _idleTimeout: 1,
      _onTimeout: [Function],
      _idlePrev: null,
      _idleNext: null,
      _idleStart: Sun, 28 Aug 2011 14:34:59 GMT } 
    

    But if you do a 0 duration, you don't get an _idleTimeout: property at all, which would seem to suggest that the callback is invoked immediately, though asynchronously.

    var timer = setTimeout(function(){ console.log(timer);}, 0);
    
    { repeat: 0, callback: [Function] }
    

    Furthermore, if I do simple start/end date comparison, I usually get 0 as the result of subtracting the start from the end.

    var start = Date.now();
    var timer = setTimeout(function(){ console.log(timer, Date.now() - start );}, 0);
    
    { repeat: 0, callback: [Function] } 0
    

    These tests were done using Node.js 0.5.2.

提交回复
热议问题