JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 19

What is debouncing in JavaScript?

Answer:

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, thus improving performance. A debounced function delays the processing of the event until after a specified wait time has passed since the last time it was invoked. This technique is particularly useful for optimizing event handling for actions like resizing the window, scrolling, or typing in a text input.

Here is an example demonstrating debouncing:

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

// Example usage
window.addEventListener('resize', debounce(() => {
    console.log('Window resized');
}, 500));

In this example, the debounce function ensures that the resize event handler is only called after the window has stopped resizing for 500 milliseconds, preventing multiple calls and improving performance.

Recent job openings