Why the Event Loop Exists
JavaScript is single-threaded — it has one call stack and one thread of execution. The event loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded.
Microtasks vs Macrotasks
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
// Output: Start, End, Promise, Timeout
// Promises (microtasks) have higher priority than setTimeout (macrotasks)
requestAnimationFrame
function animate() {
element.style.transform = `translateX(${position}px)`;
if (position < 500) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Practical Patterns
// Debouncing
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
// Throttling
function throttle(fn, limit) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
Key Takeaways
- JavaScript is single-threaded but non-blocking
- Microtasks (Promises) have higher priority than macrotasks (setTimeout)
- Use
requestAnimationFramefor smooth animations - Use
requestIdleCallbackfor low-priority background work