How can I debounce or throttle events using jQuery

In web development, debouncing and throttling are techniques used to limit the rate at which a function can fire. They are particularly useful for optimizing performance in event-heavy scenarios like scrolling and resizing.

Debouncing

Debouncing ensures that a function is only called after a certain period of inactivity. For example, debouncing is often used on input fields to avoid sending requests until the user has stopped typing for a specified duration.

Throttling

Throttling, on the other hand, limits the number of times a function can be called over time. This is useful for events that trigger frequently, such as scrolling or resizing.

Example of Debouncing and Throttling in jQuery

Below is an example of how to implement debouncing and throttling in jQuery:

$(document).ready(function() { // Debounce function function debounce(func, wait) { let timeout; return function(...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => func.apply(context, args), wait); }; } // Throttle function 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(() => { if ((Date.now() - lastRan) >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; } // Apply debouncing to keyup event $('#inputField').on('keyup', debounce(function() { console.log('Input value:', $(this).val()); }, 300)); // Apply throttling to scroll event $(window).on('scroll', throttle(function() { console.log('Scroll event triggered'); }, 1000)); });

jQuery debounce throttle event handling performance optimization