Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript are these calls the same in Node.js?

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?

like image 386
Nam Nguyen Avatar asked Sep 13 '13 06:09

Nam Nguyen


1 Answers

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);
like image 187
Paul Avatar answered Oct 04 '22 07:10

Paul