LearnFrenzy
Sign in Take a free test

Event Loop · Event Loop Coding Problems · Question 10

Run tasks one per event-loop turn in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Write runTasks(tasks) that runs a list of synchronous jobs one per macrotask (yielding with a setTimeout promise between them) and resolves with their results; show that a promise callback queued at the start runs before the first job, and a timer between jobs.

Solution
main.js
const nextTurn = () => new Promise((r) => setTimeout(r, 0));

async function runTasks(tasks) {
  const results = [];
  for (const [name, job] of tasks) {
    await nextTurn();                       // one job per event-loop turn
    results.push(`${name}=${job()}`);
    console.log(`ran ${name}`);
  }
  return results;
}

Promise.resolve().then(() => console.log("(microtask: runs before any job)"));
setTimeout(() => console.log("(timer task: runs between jobs)"), 0);
runTasks([
  ["square", () => 12 ** 2],
  ["reverse", () => [..."loop"].reverse().join("")],
  ["sum", () => [1, 2, 3, 4].reduce((a, b) => a + b)],
]).then((r) => console.log(r.join(" | ")));

Output Verified by running it on Node.js

(microtask: runs before any job)
(timer task: runs between jobs)
ran square
ran reverse
ran sum
square=144 | reverse=pool | sum=10

The outside timer was queued before runTasks' first nextTurn timer, so it runs first; each job then occupies its own task, leaving room for other work between jobs.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links