Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Debouncing and Throttling for Performance Optimization

Tech 1

Debouncing and Throttling Techniques

Debouncing

Debouncing delays the execution of a function until a specified period has passed without further event triggers. If the event reoccurs within this interval, the timer resets. This approach ensures that the function runs only after the event has ceased for a set duration.

Applications: Debouncing is ideal for scenarios where actions should respond after user input stops, such as search suggestions in input fields, layout adjustments on window resize, or operations triggered after scrolling ends. It minimizes unnecessary computations or DOM manipulations, enhancing performance.

Common Use Cases:
  • Real-time search suggestions (initiate search after user stops typing)
  • Layout recalculation on window resize (execute after resizing halts)
  • Scroll event handlers (perform actions after scrolling stops)
/**
 * Debounce function to limit execution frequency.
 * 
 * This function postpones the invocation of a callback until a delay period
 * elapses without further calls, resetting the timer on each new trigger.
 * Useful for handling frequent events like input or resize.
 * 
 * @param {Function} callback - The function to debounce.
 * @param {number} waitTime - Delay in milliseconds before execution.
 * @returns {Function} - A debounced version of the callback.
 */
function createDebouncer(callback, waitTime) {
    let timeoutId = null;

    return function(...args) {
        const context = this;
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            callback.apply(context, args);
        }, waitTime);
    };
}

// Example usage:
// const debouncedSearch = createDebouncer(searchFunction, 300);
// inputElement.addEventListener('input', debouncedSearch);

Throttling

Throttling restricts a function to execute at most once per defined time interval, regardless of how many times the event fires. This technique controls execution frequency to prevent performance degradation from overly frequent calls.

Applications: Throttling suits events that require periodic handling but not on every trigger, such as scroll-based loading, mouse movement tracking, or real-time data updates. It ensures consistent performance by limiting functon calls.

Common Use Cases:
  • Infinite scroll loading (load content at intervals during scrolling)
  • Game mechanics like shooting (limit action rate to avoid performance issues)
  • Real-time monitoring (refresh data at fixed intervals, e.g., every 5 seconds)
/**
 * Throttle function to regulate execution rate.
 * 
 * This function ensures the callback is invoked no more than once per specified
 * interval, using a timestamp-based approach for accuracy.
 * Effective for events like scroll or mousemove.
 * 
 * @param {Function} callback - The function to throttle.
 * @param {number} interval - Minimum time between executions in milliseconds.
 * @returns {Function} - A throttled version of the callback.
 */
function createThrottler(callback, interval) {
    let lastExecTime = 0;
    let scheduledId = null;

    return function(...args) {
        const context = this;
        const currentTime = Date.now();
        const timeSinceLastExec = currentTime - lastExecTime;
        const timeRemaining = interval - timeSinceLastExec;

        if (timeRemaining <= 0) {
            if (scheduledId) {
                clearTimeout(scheduledId);
                scheduledId = null;
            }
            callback.apply(context, args);
            lastExecTime = currentTime;
        } else if (!scheduledId) {
            scheduledId = setTimeout(() => {
                callback.apply(context, args);
                lastExecTime = Date.now();
                scheduledId = null;
            }, timeRemaining);
        }
    };
}

// Example usage:
// const throttledScroll = createThrottler(loadMoreContent, 200);
// window.addEventListener('scroll', throttledScroll);

Key Differences

  • Debouncing: Executes after a pause in events, reducing calls by waiting for inatcivity.
  • Throttling: Executes at regular intervals, controlling frequency by limiting calls over time.

Selection depends on specific requirements: use debouncing for tasks that should respond after user actions stop (e.g., search inputs), and throttling for tasks needing controlled execution rates (e.g., scroll events).

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.