Using setTimeout for Performance Optimization in JavaScript
setTimeout can break long tasks, defer work, and keep the UI responsive. Here are practical patterns.
Using setTimeout for Performance Optimization in JavaScript
setTimeout is not just for delays. It is a powerful tool for keeping the UI responsive by breaking up long tasks and deferring non-critical work.
Problem: Long Tasks Block the UI
function processAll(items) { items.forEach(process); // if items is 100,000, the UI freezes for seconds } `` The main thread is blocked. Clicks, animations, and input do not respond. ### Fix 1: Chunk with `setTimeout` ```js function processAll(items, chunkSize = 100) { let i = 0; function chunk() { const end = Math.min(i + chunkSize, items.length); for (; i < end; i++) { process(items[i]); } if (i < items.length) { setTimeout(chunk, 0); // yield to the browser between chunks } } chunk(); } `` Each chunk processes 100 items, then yields via `setTimeout(cb, 0)`. The browser can render and respond to input between chunks. ### Fix 2: Defer Non-Critical Work ```js // show the UI immediately renderUI(); // defer analytics, logging, preloading setTimeout(() => { sendAnalytics(); preloadImages(); }, 0); `` The user sees the UI immediately. Non-critical work runs after the browser paints. ### Fix 3: Debounce Input ```js function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } const search = debounce((q) => fetchResults(q), 300); input.addEventListener("input", (e) => search(e.target.value)); `` `debounce` uses `setTimeout` to delay the action until the user stops typing for 300ms. This prevents excessive API calls. ### Fix 4: Throttle Scroll/Resize ```js function throttle(fn, delay) { let last = 0; let timer; return (...args) => { const now = Date.now(); if (now - last >= delay) { last = now; fn(...args); } else { clearTimeout(timer); timer = setTimeout(() => { last = now; fn(...args); }, delay - (now - last)); } }; } const onScroll = throttle(() => updateLayout(), 100); window.addEventListener("scroll", onScroll); `` `throttle` limits the function to at most once per 100ms, preventing performance issues from rapid scroll/resize events. ### Modern Alternatives - **`requestIdleCallback`**: runs work when the browser is idle (better than `setTimeout(cb, 0)` for low-priority work). - **`scheduler.postTask`**: a newer API for prioritized task scheduling. - **Web Workers**: move heavy computation off the main thread entirely. ### The Takeaway `setTimeout` is a performance tool: chunk long tasks to keep the UI responsive, defer non-critical work, debounce input, and throttle scroll/resize. For modern alternatives, use `requestIdleCallback`, `scheduler.postTask`, or Web Workers for heavy computation.
By breaking long tasks into chunks (yielding between chunks), deferring non-critical work until after the browser paints, debouncing input to prevent excessive calls, and throttling rapid events like scroll and resize.
Process a batch of items, then call setTimeout(chunk, 0) to schedule the next batch. This yields to the browser between chunks, letting it render and respond to input. Adjust the chunk size to balance speed and responsiveness.
debounce delays the action until the user stops typing for a specified delay. Each keystroke clears the previous timer and sets a new one. The action runs only after the pause, preventing excessive API calls.
requestIdleCallback runs work when the browser is idle (better for low-priority work). scheduler.postTask is a newer API for prioritized scheduling. Web Workers move heavy computation off the main thread entirely.
So the browser can paint the UI immediately and respond to user input. Non-critical work like analytics, logging, and preloading can run after the paint, improving perceived performance without blocking the user experience.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

