实现说明
各个操作都建立在顶层绑定之上:panel、handle。
使用要点
- 这是浏览器侧代码——
document在 Node 里解析不到。 - 每一步打印都带着自己的标签:
insights computed at idle time、second idle task、cancelled the second idle task before it ran。
常见问题
「requestIdleCallback 推迟后台工作」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。
核心语句
const panel = document.querySelector("#insights");
panel.textContent = "insights ready";
cancelIdleCallback(handle);
代码示例
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");