JS single-threaded nhưng xử lý async nhờ event loop.
Quy trình:
- Chạy hết sync code trên Call Stack.
- Xử lý hết Microtask queue.
- Browser có thể render.
- Lấy 1 Macrotask.
- Quay lại bước 2
javascript
console.log('1 sync');
setTimeout(() => console.log('4 macrotask'), 0);
Promise.resolve()
.then(() => console.log('2 microtask'))
.then(() => console.log('3 microtask 2'));
console.log('1b sync');
// Output: 1 sync → 1b sync → 2 microtask → 3 microtask 2 → 4 macrotaskMicrotasks luôn ưu tiên hơn macrotasks — Promise.resolve().then() chạy trước setTimeout(fn, 0).