title: How is setTimeout implemented in node.js
body: <p>I was wondering if anybody knows how <a href="http://nodejs.org/api/timers.html#timers_settimeout_callback_delay_arg" rel="noreferrer">setTimeout</a> is implemented in node.js. I believe I have read somewhere that this is not part of V8. I quickly tried to find the implementation, but could not find it in the source(BIG).I for example found this <a href="https://github.com/joyent/node/blob/master/lib/timers.js" rel="noreferrer">timers.js</a> file, which then for example links to <a href="https://github.com/joyent/node/blob/master/src/timer_wrap.cc" rel="noreferrer">timer_wrap.cc</a>. But these file do not completely answer all of my questions.</p>
  
  <ul>
  <li>Does V8 have <code>setTimeout</code> implementation? I guess also from the source the answer is no.</li>
  <li><p>How is <code>setTimeout</code> implemented? javascript or native or combination of both? From timers.js I assume something along the line of both:</p>
  
  <pre><code>var Timer = process.binding('timer_wrap').Timer;`
  </code></pre></li>
  <li><p>When adding multiple timers(setTimeout) how does node.js know which to execute first? Does it add all the timers to a collection(sorted)? If it is sorted then finding the timeout which needs to be executed is O(1) and O(log n) for insertion? But then again in timers.js I see them use a linkedlist?</p></li>
  <li>But then again adding a lot of timers is not a problem at all?</li>
  <li><p>When executing this script:</p>
  
  <pre><code>var x = new Array(1000),
      len = x.length;
  
  /**
   * Returns a random integer between min and max
   * Using Math.round() will give you a non-uniform distribution!
   */
  function getRandomInt (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
  var y = 0;
  
  for (var i = 0; i &lt; len; i++) {
      var randomTimeout = getRandomInt(1000, 10000);
  
      console.log(i + ', ' + randomTimeout + ', ' + ++y);
      setTimeout(function () {
          console.log(arguments);
      }, randomTimeout, randomTimeout, y);
  }
  </code></pre>
  
  <p>you get a little bit of CPU usage but not that much?</p></li>
  <li>I  am wondering if I implement all these callbacks one by one in a sorted list if I will get better performance?</li>
  </ul>