Skip to content

Instantly share code, notes, and snippets.

@hamzaerbay
Last active August 27, 2023 22:48
Show Gist options
  • Save hamzaerbay/21d13e039685185e5dda20ecf9d475e1 to your computer and use it in GitHub Desktop.
Save hamzaerbay/21d13e039685185e5dda20ecf9d475e1 to your computer and use it in GitHub Desktop.
Debounce
/**
* Creates and returns a debounced version of the provided function.
* The debounced version of the function will delay the invoking of the
* original function until after a specified number of milliseconds have
* passed since the last time the debounced function was invoked.
*
* @param {Function} callback - The function to debounce.
* @param {number} delay - The number of milliseconds to delay invocation.
* @returns {Function} - The debounced version of the provided function.
*/
function debounce(callback, delay) {
// Store the reference of the timeout.
let timeout;
// Return a new function that wraps the original function
// with the debounce logic.
return function(...args) {
// Clear the previous timeout if it exists. This means if the function
// gets called again within the delay, it will reset the timer.
clearTimeout(timeout);
// Set up a new timeout to invoke the callback after the delay.
timeout = setTimeout(() => {
// Use the apply method to call the callback with the correct context (`this`)
// and pass any arguments to it.
callback.apply(this, args)
}, delay);
}
}
const searchInput = document.querySelector("#searchInput");
// Function to handle the input changes
function handleInputChange(event) {
const query = event.target.value;
console.log("Searching for:", query);
// Let's pretend this would call some API or perform some filtering
// Do the actual search here...
}
// Debounce the input change handler
const debouncedInputChange = debounce(handleInputChange, 300);
// Attach the debounced function to the input change event
searchInput.addEventListener("input", debouncedInputChange);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment