Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - requestIdleCallback和setImmediate之间的区别?(Differences between requestIdleCallback and setImmediate?)

There are currently 2 different API's aimed at breaking tasks up into scheduled callback functions.

(当前有两种不同的API,旨在将任务分解为计划的回调函数。)

To my knowledge there are no JavaScript runtimes (browser or Node) which currently implement both features.

(据我所知,目前没有实现两个功能的JavaScript运行时(浏览器或Node)。)

I would like to better understand how the two features compare.

(我想更好地了解这两个功能之间的比较。)

I realize that requestIdleCallback has a timeout option which can be used to allow the browser to decide when to call it, and passes a IdleDeadline object to the callback where setImmediate passed any supplied arguments, but other than that how do these API's differ?

(我意识到requestIdleCallback具有timeout选项,可用于允许浏览器决定何时调用它,并将IdleDeadline对象传递给setImmediate传递了任何提供的参数的回调,但是setImmediate ,这些API有何不同?)

For example, are the following two examples functionally identical?

(例如,以下两个示例在功能上是否相同?)

setImmediate(function() {
    // Do something.
});
requestIdleCallback(function() {
    // Do something.
}, {timeout: 0});

What about in the case where multiple callbacks are registered but the first one runs longer than the idle time?

(如果注册了多个回调但第一个回调的运行时间比空闲时间长,该怎么办?)

  ask by Alexander O'Mara translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

setTimeout will wait for a time to pass, then it will execute the callback.

(setTimeout将等待一段时间,然后将执行回调。)

requestIdleCallback will wait for the main thread to be idle before executing the callback.

(requestIdleCallback将在执行回调之前等待主线程空闲。)

Meaning that it won't slow animations, user can still click buttons and type into inputs.

(这意味着它不会减慢动画的速度,用户仍然可以单击按钮并输入内容。)

How to choose between setTimeout and requestIdleCallback?

(如何在setTimeout和requestIdleCallback之间进行选择?)

setTimeout is best used when the callback must execute (Example: Sending data to an analytics server or logging out the user).

(setTimeout最适合在必须执行回调的情况下使用(例如:将数据发送到分析服务器或注销用户)。)

requestIdleCallback is best for when you don't want to hurt the user experience in the cost of executing the callback (Example: Rerendering the DOM).

(requestIdleCallback最适合您不希望在执行回调的成本上损害用户体验的情况下(例如:重新渲染DOM)。)

Keep in mind that requestIdleCallback is still experimental.

(请记住,requestIdleCallback仍处于试验阶段。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...