NodeJS Program to Task Queue With setImmediate with Explanation
NodeJS
Hard
Async & Event Loop
27 views
1 min read
82 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around task, setimmediate, done. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Process an array of tasks without blocking the event loop.
Input Format
No input.
Output Format
Print DONE.
Constraints
Use setImmediate to yield between chunks.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const tasks = Array.from({ length: 5000 }, (_, i) => i + 1);
let sum = 0;
function runChunk() {
const chunk = tasks.splice(0, 500);
for (const x of chunk) sum += x;
if (tasks.length) setImmediate(runChunk);
else console.log('DONE');
}
runChunk();
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Process an array of tasks without blocking the event loop.
Input / Output
Constraints
Use setImmediate to yield between chunks.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
const tasks = Array.from({ length: 5000 }, (_, i) => i + 1);
let sum = 0;
function runChunk() {
const chunk = tasks.splice(0, 500);
for (const x of chunk) sum += x;
if (tasks.length) setImmediate(runChunk);
else console.log('DONE');
}
runChunk();
Solutions (0)
No solutions submitted yet. Be the first!