Skip to content

Instantly share code, notes, and snippets.

@kelgendy1204
Created June 24, 2024 10:27
Show Gist options
  • Save kelgendy1204/d5bf87d67dfaaac71643d9d491af2101 to your computer and use it in GitHub Desktop.
Save kelgendy1204/d5bf87d67dfaaac71643d9d491af2101 to your computer and use it in GitHub Desktop.
Blocking event loop in nodejs
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