
Use idle callbacks for tasks which don't have high priority.Getting the most out of idle callbacksīecause idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them. If you stay within the limit given, you can make the user's experience much better. Window.requestIdleCallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread.īecause event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. It's an extremely busy chunk of code, and your main JavaScript code may run right inside this thread along with all of this.


In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. This code draws any pending updates to the Document currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. The main thread of a Web browser is centered around its event loop.
