Posted January 25Jan 25 You are reading Part 29 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]IntroductionWhen handling frequent events like scrolling, resizing, and keystrokes, executing event handlers continuously can lead to performance issues. Debouncing and throttling are two optimization techniques that improve efficiency by controlling how often event handlers execute.1. What is Debouncing?Debouncing delays the execution of a function until a specified time has passed since the last event. It is useful for scenarios where the action should only be triggered once after user input stops (e.g., search inputs, window resizing).Example: Implementing Debounce Functionfunction debounce(func, delay) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), delay); }; } Use Case: Debouncing an Input Fieldfunction fetchSearchResults(query) { console.log("Fetching results for:", query); } const input = document.getElementById("search"); input.addEventListener("input", debounce(event => fetchSearchResults(event.target.value), 500)); The event fires immediately when typing starts, but execution waits until 500ms after the last keystroke.Prevents excessive API calls while typing.2. What is Throttling?Throttling ensures that a function executes at most once in a specified time interval, ignoring extra calls within that period. It is ideal for rate-limiting frequent events like scrolling and resizing.Example: Implementing Throttle Functionfunction throttle(func, limit) { let lastCall = 0; return function(...args) { let now = Date.now(); if (now - lastCall >= limit) { lastCall = now; func.apply(this, args); } }; } Use Case: Throttling Scroll Eventsfunction handleScroll() { console.log("Scroll event triggered"); } window.addEventListener("scroll", throttle(handleScroll, 1000)); The handleScroll function executes at most once per second.Prevents excessive calls while the user scrolls rapidly.3. When to Use Debounce vs Throttle?Use CaseUse DebounceUse ThrottleSearch input field✅❌Window resizing✅❌Infinite scrolling❌✅Button clicks❌✅API request handling✅❌Animations on scroll❌✅4. Combining Debounce and ThrottleSometimes, combining both techniques enhances performance. For instance, throttling ensures periodic execution, while debouncing prevents excess calls when the user stops an action.Example: A Function That Uses Bothconst optimizedResize = debounce(throttle(() => console.log("Resized!"), 500), 1000); window.addEventListener("resize", optimizedResize); Ensures at least 500ms between calls but waits 1000ms after the last resize event before executing.You are reading Part 29 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.