zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time

JavaScript to an use Time at Schedule Tasks
2023-09-14 08:59:14 时间

JavaScript is single-threaded, which can present some problems when creating an interactive user experience. If JavaScript runs too long while a user is attempting to interact with a page, it can cause noticeable jank or lag, which degrades the experience. requestIdleCallback is a DOM API that allows you to schedule a JavaScript function to be run when the page thread is idle, so your JavaScript doesn't get in the way of the user.

 

let id = requestIdleCallback(
  () => {
    console.log("idle callback called");
  },
  { timeout: 2000 } // the function must be run within 2 seconds
);

cancelIdleCallback(id);