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.
Code
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.
documentexist 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
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.