Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Debounce and Throttle for JavaScript Performance Optimization

Tech 1

Debouncing and Throttling

High-frequency event triggers, such as scrolling or rapid clicks, can lead to excessive execution of event handlers, wasting browser resources. These techniques manage execution frequency to improve performance.

Debouncing limits execution to a single occurrence, either the first or last in a series. Throttling reduces execution to a defined rate, preventing multiple triggers within a short interval.

Debounce Implementation

function debounceHandler(callback, delay = 300, immediate = false) {
    if (typeof callback !== 'function') {
        throw new Error('Callback must be a function');
    }
    let timeoutId = null;
    return function(...params) {
        const context = this;
        const shouldCallNow = immediate && !timeoutId;
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            timeoutId = null;
            if (!immediate) {
                callback.apply(context, params);
            }
        }, delay);
        if (shouldCallNow) {
            callback.apply(context, params);
        }
    };
}

function logClick(event) {
    console.log('Button clicked', this, event);
}

const button = document.getElementById('actionButton');
button.addEventListener('click', debounceHandler(logClick, 200, false));

Throttle Implementation

function throttleHandler(callback, interval = 400) {
    if (typeof callback !== 'function') {
        throw new Error('Callback must be a function');
    }
    let lastCallTime = 0;
    let scheduledCall = null;
    return function(...params) {
        const context = this;
        const currentTime = Date.now();
        const timeSinceLastCall = currentTime - lastCallTime;
        const remainingTime = interval - timeSinceLastCall;
        if (remainingTime <= 0) {
            clearTimeout(scheduledCall);
            scheduledCall = null;
            callback.apply(context, params);
            lastCallTime = currentTime;
        } else if (!scheduledCall) {
            scheduledCall = setTimeout(() => {
                clearTimeout(scheduledCall);
                scheduledCall = null;
                callback.apply(context, params);
                lastCallTime = Date.now();
            }, remainingTime);
        }
    };
}

function logScroll() {
    console.log('Page scrolled');
}

window.addEventListener('scroll', throttleHandler(logScroll, 600));

Optimizing Conditional Logic

Reduce nested if-else statements by returning early for invalid conditions, which minimizes execution overhead.

function validateModule(moduleName, chapterNumber) {
    const validModules = ['ES2016', 'Engineering', 'Vue', 'React', 'Node'];
    if (!moduleName) {
        console.log('Module information required');
        return;
    }
    if (!validModules.includes(moduleName)) {
        return;
    }
    console.log('Accessible module');
    if (chapterNumber > 5) {
        console.log('VIP subscription needed for this content');
    }
}
validateModule('ES2016', 6);

Improving Loop Efficiency

Cache values outside loops to avoid repeated calculations and consider reverse iteration with while loops for fixed-length arrays.

function iterateArray() {
    const items = ['alpha', 'beta', 'gamma'];
    const total = items.length;
    for (let i = 0; i < total; i++) {
        console.log(items[i]);
    }
}
iterateArray();

function reverseIterate() {
    const items = ['alpha', 'beta', 'gamma'];
    let index = items.length;
    while (index--) {
        console.log(items[index]);
    }
}
reverseIterate();

Data Declaration Performance

Use object literals instead of constructors for better performance, as they avoid function calls and unnecessary overhead.

function createObjectLiteral() {
    return {
        title: 'Performance',
        value: 100,
        description: 'Optimization tips'
    };
}
console.log(createObjectLiteral());

function createObjectConstructor() {
    const obj = new Object();
    obj.title = 'Performance';
    obj.value = 100;
    obj.description = 'Optimization tips';
    return obj;
}
console.log(createObjectConstructor());

For strings, prefer literals over the String construtcor to avoid implicit conversions and memory waste.

const textLiteral = 'Example text';
const textConstructor = new String('Example text');
console.log(textLiteral);
console.log(textConstructor);

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.