requestIdleCallback Defers Background Work

requestIdleCallback schedules non-urgent work for idle time with a timeout floor, and cancelIdleCallback drops the task before it ever runs.

JavascriptResilience

Code

javascriptsnippet
16 lines
const panel = document.querySelector("#insights");

// 非紧急计算推迟(defer)到浏览器空闲时段:输入响应优先,timeout 兜底避免饿死
requestIdleCallback(
  () => {
    panel.textContent = "insights ready";
    console.log("insights computed at idle time");
  },
  { timeout: 2000 },
);

// 需要取消时拿到句柄:组件卸载前清理
const handle = requestIdleCallback(() => console.log("second idle task"));
cancelIdleCallback(handle);
console.log("cancelled the second idle task before it ran");

How the snippet works

Module-level bindings hold the data — panel, handle — with no function scope in between.

Caveats

  • Nothing to install: the snippet stays inside the standard library.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

The demo output is labeled (insights computed at idle time, second idle task, cancelled the second idle task before it ran), so every printed line maps back to its originating operation.

Statements that matter

const panel = document.querySelector("#insights");
panel.textContent = "insights ready";
cancelIdleCallback(handle);

Interactive Tools for This Topic

FAQ

Does requestIdleCallback Defers Background Work run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.