Skip to content

Instantly share code, notes, and snippets.

@solanoepalacio
Last active July 17, 2020 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solanoepalacio/26e60253afaf793615ef2ad115a45903 to your computer and use it in GitHub Desktop.
Save solanoepalacio/26e60253afaf793615ef2ad115a45903 to your computer and use it in GitHub Desktop.
event-loop
/**
* Shows how the event loop can be delayed to the execution of a timer.
* inspired on node-js docs example: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
*/
'use-strict';
const { spawn } = require('child_process');
// Create a task that takes 95ms to complete
new Promise((resolve) => {
console.time('sleep');
spawn('sleep', ['0.085']).on('close', () => {
console.log('closed');
console.timeEnd('sleep');
resolve();
});
}).then(() => {
console.log('then');
// block the thread for 10s
const startCallback = Date.now();
while (Date.now() - startCallback < 10) {
1 + 1 // nothing, really...
}
});
let timeoutScheduled = Date.now();
setTimeout(() => {
const delay = Date.now() - timeoutScheduled;
console.log(`${delay} ms have passed since I was scheduled`);
}, 100);
'done'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment