Last active
July 17, 2020 02:38
-
-
Save solanoepalacio/26e60253afaf793615ef2ad115a45903 to your computer and use it in GitHub Desktop.
event-loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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