requestIdleCallback 和 setImmediate 的区别?

编程入门 行业动态 更新时间:2024-10-28 15:26:30
本文介绍了requestIdleCallback 和 setImmediate 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

目前有 2 种不同的 API 旨在将任务分解为预定的回调函数.

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

setImmediate(非标准)requestIdleCallback(实验性) setImmediate (non-standard) requestIdleCallback (experimental)

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

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

我想更好地了解这两个功能的比较.我意识到 requestIdleCallback 有一个 timeout 选项,可用于允许浏览器决定何时调用它,并将 IdleDeadline 对象传递给setImmediate 传递任何提供的参数的回调,但除此之外,这些 API 有何不同?

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?

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

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?

推荐答案

setTimeout 会等待一段时间过去,然后执行回调.

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

requestIdleCallback 将等待主线程 在执行回调之前处于空闲状态.这意味着它不会减慢动画速度,用户仍然可以点击按钮并输入输入内容.

requestIdleCallback will wait for the main thread to be idle before executing the callback. Meaning that it won't slow animations, user can still click buttons and type into inputs.

如何在 setTimeout 和 requestIdleCallback 之间进行选择?setTimeout 最好在必须执行回调时使用(例如:将数据发送到分析服务器或注销用户).requestIdleCallback 最适用于您不想因执行回调而损害用户体验的情况(例如:重新渲染 DOM).

How to choose between setTimeout and requestIdleCallback? setTimeout is best used when the callback must execute (Example: Sending data to an analytics server or logging out the user). 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 仍处于试验阶段.

Keep in mind that requestIdleCallback is still experimental.

这篇关于requestIdleCallback 和 setImmediate 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 11:19:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1393287.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   requestIdleCallback   setImmediate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!