'Differences between requestIdleCallback and setImmediate?

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

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

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?



Solution 1:[1]

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

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.

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).

Keep in mind that requestIdleCallback is still experimental.

Solution 2:[2]

requestIdleCallback won't execute when document.visibilityState === 'hidden', it will execute all callback at once when it become visible.

At least in electron's browser view.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Genshaft
Solution 2 ???