6

I'm wondering if these two blocks of code are the same in Node.js?

// Style 1
setTimeout(function () {
  console.log('hello');
}, 0);


// Style 2
console.log('hello');

Since above I'm passing 0 for the timeout, there should be no waiting time. Is it identical to just calling console.log('hello'); directly without using setTimeout?

Paul
  • 139,544
  • 27
  • 275
  • 264
Nam Nguyen
  • 5,668
  • 14
  • 56
  • 70

2 Answers2

8

They are different, the first adds the function to the event queue, so that it can execute as soon as it gets a chance after the current execution path completes. The second will execute it immediately.

For example:

console.log('first');

setTimeout(function(){
  console.log('third');
}, 0);

console.log('second');

The order that those are printed in is well defined, you could even do something slow (but synchronous) before printing 'second'. It's guaranteed that console.log('second'); will still execute before the callback to setTimeout does:

console.log('first');

setTimeout(function () {
  console.log('third'); // Prints after 8 seconds
}, 0);

// Spinlock for 3 seconds
(function(start){ while(new Date - start < 3000); })(new Date);

console.log('second'); // Prints after 3 seconds, but still before 'third'

// Spinlock for 5 seconds
(function(start){ while(new Date - start < 5000); })(new Date);
Paul
  • 139,544
  • 27
  • 275
  • 264
  • 2
    @NamNguyen Yes, it is true for node.js as well as web browsers. – Paul Sep 13 '13 at 07:00
  • ic and thanks. so these two function are different, no matter web or node.js. Interesting, learn new thing! – Nam Nguyen Sep 13 '13 at 07:03
  • good stuff. The result of the script will print out in order of: first, second, & third – Nam Nguyen Sep 13 '13 at 07:09
  • 1
    It's also worth mentioning that if you *just* want the behavior described above (on Node.js), [`process.nextTick(...)`](http://nodejs.org/api/process.html#process_process_nexttick_callback) is a more efficient alternative to `setTimeout(..., 0)` because it doesn't involve the overhead of timer scheduling. – Matt Patenaude Sep 17 '13 at 03:13
-3

Strictly speaking they are not exactly the same - setTimeout gives the browser a chance to "catch up" with any tasks that it desperately needs to do. But as far as we're normally concerned, 99% of the time they will do the same thing.

Rocklan
  • 7,888
  • 3
  • 34
  • 49