Why does using setTimeout(fn, 0) help avoid blocking the UI, and why does creating many promises (microtasks) not? What is the difference between macro-tasks and micro-tasks in the Event Loop?
sobes.tech AI
Answer from AI
setTimeout(fn, 0) places the function in the macro task queue, which will be executed after the current call stack and all microtasks are finished. This allows the browser to handle other events, such as updating the UI, before executing this function.
Promises create microtasks, which are executed immediately after the current code and before the next macro task. If many microtasks are created in a row, they will execute one after another without pauses, blocking UI updates.
Difference between macro tasks and microtasks:
- Macro tasks: setTimeout, setInterval, DOM events, I/O. After executing a macro task, the browser can update the UI.
- Microtasks: promises, MutationObserver. They execute immediately after the current script and before the next macro task.
Therefore, using setTimeout(fn, 0) allows the browser to insert a pause between tasks, giving time for re-rendering, while a large number of promises in a row blocks the execution thread and the UI does not update.