WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

JavaScript Β· Intermediate Β· question 40 of 100

Can you explain the concept of debouncing and throttling in JavaScript, and why they are important for performance optimization?

πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

Debouncing and throttling are two techniques used in JavaScript to improve performance and reduce the number of unnecessary function calls. They are both used to control the rate at which a function is executed, but they differ in their implementation and the problem they address.

Debouncing is a technique that delays the execution of a function until after a certain amount of time has elapsed since the last time the function was called. It is useful for situations where a function is called repeatedly in a short amount of time, such as with an input field that triggers a search function on every keystroke. By debouncing the function, we can delay the execution until the user has finished typing, which can improve performance and reduce the number of unnecessary function calls.

Here is an example of how to debounce a function in JavaScript:

    function debounce(func, delay) {
        let timeoutId;
        
        return function(...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
    }
    
    function search(query) {
        console.log(`Searching for "${query}"...`);
    }
    
    const debouncedSearch = debounce(search, 500);
    
    document.getElementById("searchInput").addEventListener("input", function(event) {
        debouncedSearch(event.target.value);
    });

In this example, the debounce function takes a function and a delay time as arguments, and returns a new function that debounces the original function. The debounced function uses setTimeout to delay the execution of the original function until after the delay time has elapsed since the last time it was called.

Throttling is a technique that limits the rate at which a function can be called. It is useful for situations where a function is called frequently, but we want to limit the number of times it is executed to prevent performance issues. For example, when scrolling a web page, we may want to limit the number of times a function that updates the page is called to prevent jank.

Here is an example of how to throttle a function in JavaScript:

    function throttle(func, delay) {
        let lastTime = 0;
        
        return function(...args) {
            const currentTime = Date.now();
            
            if (currentTime - lastTime >= delay) {
                func.apply(this, args);
                lastTime = currentTime;
            }
        };
    }
    
    function updatePage() {
        console.log("Updating page...");
    }
    
    const throttledUpdatePage = throttle(updatePage, 500);
    
    window.addEventListener("scroll", throttledUpdatePage);

In this example, the throttle function takes a function and a delay time as arguments, and returns a new function that throttles the original function. The throttled function uses the current time and the last time the function was called to determine whether enough time has elapsed to execute the function again.

In summary, debouncing and throttling are important techniques in JavaScript for performance optimization. They help to control the rate at which functions are executed, which can improve performance, reduce the number of unnecessary function calls, and prevent jank in user interfaces.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview β€” then scores it.
πŸ“ž Practice JavaScript β€” free 15 min
πŸ“• Buy this interview preparation book: 100 JavaScript questions & answers β€” PDF + EPUB for $5

All 100 JavaScript questions Β· All topics