Javascript - are these calls the same in Node.js?

I am wondering if these two code blocks in Node.js match?

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

Since above I pass 0 for a timeout, there should not be a wait time. This is identical to just calling console.log('hello'); directly without using setTimeout?

+6
source share
2 answers

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

For instance:

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

The order in which they are printed is clearly defined, you can even do something slow (but synchronous) before printing “second”. This ensured that console.log('second'); will be executed before setTimeout callback:

 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); 
+8
source

Strictly speaking, they are not quite the same - setTimeout gives the browser the ability to “catch up” with any tasks that desperately need to be done. But, as far as we are usually concerned, in 99% of cases they will do the same.

-2
source

Source: https://habr.com/ru/post/953752/


All Articles