What is the event loop in JavaScript?
JavaScript runs one thing at a time, on the call stack. Timers and network requests are done by the browser in the background. When they finish, their callbacks wait in a queue, and the event loop moves them to the call stack when the stack is empty. Promise callbacks (microtasks) go before timer callbacks (macrotasks).
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
Output:
Tutorials Class - Output Window
1
4
3
2
The normal code runs first (1, 4), then the promise callback (3), then the timer callback (2), even with 0 milliseconds.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |