Created
February 10, 2026 07:07
-
-
Save RussellJapheth/4272b18eb4742c41c42a5c3218c4bce0 to your computer and use it in GitHub Desktop.
Debounce a function in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Creates a debounced version of a function that delays execution until after | |
| * 'delay' milliseconds have elapsed since the last time it was invoked. | |
| * | |
| * @param {Function} fn - The function to execute. | |
| * @param {number} [delay=300] - The delay in milliseconds. | |
| * @returns {Function} - The debounced function with a .cancel() method. | |
| */ | |
| export function debounce(fn, delay = 300) { | |
| let timeoutId = null; | |
| function debounced(...args) { | |
| // If a timer is already running, clear it to "reset" the clock | |
| if (timeoutId) { | |
| clearTimeout(timeoutId); | |
| } | |
| // Schedule the function execution | |
| timeoutId = setTimeout(() => { | |
| // Execute fn with the correct context ('this') and arguments | |
| fn.apply(this, args); | |
| // Reset timeoutId once executed | |
| timeoutId = null; | |
| }, delay); | |
| } | |
| /** | |
| * Allows manual cancellation of the pending execution. | |
| */ | |
| debounced.cancel = () => { | |
| if (timeoutId) { | |
| clearTimeout(timeoutId); | |
| timeoutId = null; | |
| } | |
| }; | |
| return debounced; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { debounce } from './debounce.js'; | |
| // 1. The function we want to limit | |
| function performSearch(query) { | |
| console.log(`Searching API for: ${query}...`); | |
| // This is where your fetch() logic would go | |
| } | |
| // 2. Wrap it in a debounce (wait 500ms after the last keystroke) | |
| const debouncedSearch = debounce((event) => { | |
| const query = event.target.value; | |
| if (query.length > 2) { | |
| performSearch(query); | |
| } | |
| }, 500); | |
| // 3. Attach it to an input field | |
| const searchInput = document.querySelector('#search-bar'); | |
| searchInput.addEventListener('input', debouncedSearch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment