Quinix

(This page might be a bit more readable if you enable 1st-party CSS.)

Asyncronicity and a single thread

While writing about input and asynchrony I wrote up the following simple example to verify my understanding of how output flushing works in Node.

import process from 'process';
process.stdout.write('Hi!\n', function(){
  process.stdout.write('Done!\n');
});
process.stdout.write('Waiting!\n');

let s = 0;
for(let i = 0; i < 1000000000; i++){
  // Just some random garbage to slow things down.
  s = (s + i) / (s + 1);
}

If you run this code you’ll see the following output, as expected:

Hi!
Waiting!
Done!

The interesting thing you’ll note, however, is that there is indeed a pause after “Waiting!” and before “Done!” – that’s when the single thread of execution is “blocked”, spinning through the pointless for loop.

« Back