completefrontend

Write the codeMedium

Write runWhenIdle(task), which runs a task in an idle callback, or after a timeout, and can be cancelled.

The tea shop wants to save recently viewed teas and warm a cache without slowing anything down. Write runWhenIdle(task, options), which calls task(deadline) once, when the browser is idle, and returns a cancel function. Calling cancel() before the task has run means it never runs; calling it afterwards, or twice, does nothing.

Where the browser has requestIdleCallback, run the task in an idle callback, asked for with { timeout: options.timeout } (2000 ms when it isn't given), so a page that's never idle still runs it once the timeout has passed. Pass the task the browser's IdleDeadline. Cancel it with cancelIdleCallback.

Where it doesn't, as in Safari, run the task in a task of its own with a 0 ms setTimeout, and pass it a deadline of your own: didTimeout is false, and timeRemaining() counts down from 50 ms from when the task starts, never below 0. Cancel it with clearTimeout. Check for requestIdleCallback each time runWhenIdle is called, not once when the script loads.

const cancel = runWhenIdle((deadline) => {
  if (deadline.timeRemaining() > 5) saveRecentTeas();
});
// The visitor left the tea page before the browser was idle:
cancel();
Write this: solution.js
function runWhenIdle(task, options = {}) {
  // Today the task runs in the next task, idle or not, gets no deadline, and can't be cancelled.
  setTimeout(() => task(), 0);
  return () => {};
}
The tests your code must pass
  • runs the task in an idle callback, not right away
  • asks with a 2000 ms timeout, or the one given, and passes the browser's deadline
  • on a page that's never idle, runs once the timeout has passed
  • cancel() before it runs stops it, and afterwards does nothing
  • without requestIdleCallback, runs in a 0 ms timeout with a 50 ms deadline of its own
  • cancel() works without requestIdleCallback too

Try it in the editor

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…