Jump to content

Featured Replies

Posted

You are reading Part 29 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 5]

Introduction

When 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 Function

function debounce(func, delay) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), delay);
    };
}

Use Case: Debouncing an Input Field

function 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 Function

function 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 Events

function 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 Case

Use Debounce

Use Throttle

Search input field

Window resizing

Infinite scrolling

Button clicks

API request handling

Animations on scroll

4. Combining Debounce and Throttle

Sometimes, 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 Both

const 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]

  • Views 37
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.