Created
June 24, 2024 10:27
-
-
Save kelgendy1204/d5bf87d67dfaaac71643d9d491af2101 to your computer and use it in GitHub Desktop.
Blocking event loop in nodejs
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
function blockForSeconds(seconds) { | |
const startTime = Date.now(); | |
let endTime = startTime; | |
while (endTime - startTime < seconds * 1000) { | |
endTime = Date.now(); | |
} | |
} | |
function run() { | |
const startTime = performance.now(); | |
setTimeout(() => { | |
blockForSeconds(2); | |
const endTime = performance.now(); | |
const executionTime = endTime - startTime; | |
console.log(`1 second timeout with block for 2 seconds execution time: ${executionTime.toFixed(3)} milliseconds`); | |
}, 1000); | |
setTimeout(() => { | |
const endTime = performance.now(); | |
const executionTime = endTime - startTime; | |
console.log(`1.5 second timeout without block execution time: ${executionTime.toFixed(3)} milliseconds`); | |
}, 1500); | |
} | |
run(); | |
/* | |
* Results: | |
* 1 second timeout with block for 2 seconds execution time: 3000.030 milliseconds | |
* 1.5 second timeout without block execution time: 3004.486 milliseconds | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment