completefrontend

Predict the outputMedium

Which of these tasks are long, and what's the blocking time?

A trace of the tea shop's menu page shows six main-thread tasks. The code picks out the long ones the way the Long Tasks API does, adds up how long the main thread was busy and how much of that was blocking time, the part of each task past 50 ms, and then does the same with the reviews widget's work split into four tasks. What does it log?

The code
// The main thread's tasks while Leaf and Kettle's menu page loads, from a trace, in the order they ran.
// Durations are whole milliseconds, as the Long Tasks API reports them.
const tasks = [
  { name: "parse the HTML", duration: 31 },
  { name: "run menu.js", duration: 182 },
  { name: "build the tea grid", duration: 50 },
  { name: "analytics timer", duration: 49 },
  { name: "reviews widget", duration: 96 },
  { name: "a click handler", duration: 12 },
];
 
// The Long Tasks API reports a task of 50 ms or more.
const long = tasks.filter((task) => task.duration >= 50);
for (const task of long) {
  console.log(`Long: ${task.name}, ${task.duration} ms, blocking ${task.duration - 50} ms`);
}
 
// Blocking time: the part of each task past 50 ms.
const blockingTime = (durations) => durations.reduce((sum, ms) => sum + Math.max(0, ms - 50), 0);
const total = (durations) => durations.reduce((sum, ms) => sum + ms, 0);
const durations = tasks.map((task) => task.duration);
console.log(`Long tasks: ${long.length} of ${tasks.length}`);
console.log(`Busy for ${total(durations)} ms, blocking for ${blockingTime(durations)} ms`);
 
// The same work, with the reviews widget's 96 ms split into four tasks of 24 ms.
const split = [31, 182, 50, 49, 24, 24, 24, 24, 12];
console.log(`Widget split: busy for ${total(split)} ms, blocking for ${blockingTime(split)} ms`);

Practice it in the editor, with tests

The answer

Work out every line it logs, in order. Then check.

Checking your sign-in…