Skip to content

Instantly share code, notes, and snippets.

@alexander-elgin
Created October 21, 2025 09:59
Show Gist options
  • Save alexander-elgin/eaf8635895fa6215681cc82c75772df4 to your computer and use it in GitHub Desktop.
Save alexander-elgin/eaf8635895fa6215681cc82c75772df4 to your computer and use it in GitHub Desktop.
Blocked Event Loop Resolved by Worker
const getFactorial = (value) => {
let prevTimestamp = Date.now();
let currentValue = 0;
let total = 1;
while (currentValue < value) {
const now = Date.now();
if (now - prevTimestamp >= 1000) {
total *= ++currentValue;
prevTimestamp = now;
}
}
return total;
};
const originalTimestamp = Date.now();
let prevTimestamp = originalTimestamp;
let iteration = 0;
const ITERATIONS_NUMBER = 8;
const value = 6;
console.log('START');
console.log(`The factorial of ${value} is`, getFactorial(value));
while (iteration < ITERATIONS_NUMBER) {
const now = Date.now();
if (now - prevTimestamp >= 1000) {
console.log(++iteration);
prevTimestamp = now;
}
}
console.log('END after', ((Date.now() - originalTimestamp) / 1000).toFixed(1), 'sec.');
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
const getFactorial = (value) => {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, { workerData: { value } });
worker.on('message', resolve);
worker.on('error', reject);
});
};
const originalTimestamp = Date.now();
let prevTimestamp = originalTimestamp;
let iteration = 0;
const ITERATIONS_NUMBER = 8;
const value = 6;
console.log('START');
getFactorial(value).then((res) => console.log(`The factorial of ${value} is`, res));
while (iteration < ITERATIONS_NUMBER) {
const now = Date.now();
if (now - prevTimestamp >= 1000) {
console.log(++iteration);
prevTimestamp = now;
}
}
console.log('END after', ((Date.now() - originalTimestamp) / 1000).toFixed(1), 'sec.');
} else {
const { value } = workerData;
let prevTimestamp = Date.now();
let currentValue = 0;
let total = 1;
while (currentValue < value) {
const now = Date.now();
if (now - prevTimestamp >= 1000) {
total *= ++currentValue;
prevTimestamp = now;
}
}
parentPort.postMessage(total);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment