What is debouncing and throttling in JavaScript?

Debouncing and throttling are techniques used to control how often a function is executed in response to events in JavaScript. Both are commonly used to improve performance, avoid excessive function calls, and enhance user experience in web applications.

What is Debouncing?

Debouncing is a technique that ensures a function is only executed after a certain period of inactivity. It is particularly useful in situations where you want to limit the number of times a function (like an API call) is called in a short period, such as during typing in a text box or resizing a window.

Example of Debouncing

function debounce(func, delay) { let timeout; return function(...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => func.apply(context, args), delay); }; } const processInput = debounce(() => { console.log('Input processed'); }, 300);

What is Throttling?

Throttling, on the other hand, ensures that a function is not called more than once in a specified amount of time. This is useful for events that fire in quick succession, like scrolling, where you may only want to react to the event at a set frequency.

Example of Throttling

function throttle(func, limit) { let lastFunc; let lastRan; return function(...args) { const context = this; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(function() { if ((Date.now() - lastRan) >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; } const logScroll = throttle(() => { console.log('Scroll event processed'); }, 1000);

debouncing throttling JavaScript performance event handling API optimization