How does setTimeout work in Node.JS?

后端 未结 5 1007
心在旅途
心在旅途 2020-11-30 19:35

I guess that once it\'s executed it\'s on the queue, but in the queue is there any assurance it will invoke exactly after X milliseconds? Or will other heavy tasks higher on

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 20:33

    The idea of non-blocking is that the loop iterations are quick. So to iterate for each tick should take short enough a time that the setTimeout will be accurate to within reasonable precision (off by maybe <100 ms or so).

    In theory though you're right. If I write an application and block the tick, then setTimeouts will be delayed. So to answer you're question, who can assure setTimeouts execute on time? You, by writing non-blocking code, can control the degree of accuracy up to almost any reasonable degree of accuracy.

    As long as javascript is "single-threaded" in terms of code execution (excluding web-workers and the like), that will always happen. The single-threaded nature is a huge simplification in most cases, but requires the non-blocking idiom to be successful.

    Try this code out either in your browser or in node, and you'll see that there is no guarantee of accuracy, on the contrary, the setTimeout will be very late:

    var start = Date.now();
    
    // expecting something close to 500
    setTimeout(function(){ console.log(Date.now() - start); }, 500);
    
    // fiddle with the number of iterations depending on how quick your machine is
    for(var i=0; i<5000000; ++i){}
    

    Unless the interpreter optimises the loop away (which it doesn't on chrome), you'll get something in the thousands. Remove the loop and you'll see it's 500 on the nose...

提交回复
热议问题