Last active
December 22, 2023 11:12
-
-
Save PabloAballe/bf61f8cf73103407c92961029e62c33c to your computer and use it in GitHub Desktop.
Debounce Function Snippet: Implements a debounce function to limit the rate at which a function can fire.
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
| /** | |
| * Debounce Function Snippet | |
| * Brief Description: Implements a debounce function to limit the rate at which a function can fire. | |
| * | |
| * Author: Pablo Aballe | |
| * Date: 2023-12-22 | |
| */ | |
| /** | |
| * Creates a debounced version of a function. | |
| * @param {Function} func - The function to debounce. | |
| * @param {number} delay - The number of milliseconds to delay. | |
| * @returns {Function} - The debounced function. | |
| */ | |
| function debounce(func, delay) { | |
| let debounceTimer; | |
| return function() { | |
| const context = this; | |
| const args = arguments; | |
| clearTimeout(debounceTimer); | |
| debounceTimer = setTimeout(() => func.apply(context, args), delay); | |
| }; | |
| } | |
| // Usage Example | |
| window.addEventListener('resize', debounce(() => { | |
| console.log('Resize event handler called after 300ms of no resize events'); | |
| }, 300)); | |
| // Additional Notes: | |
| // Debouncing is particularly useful for rate-limiting execution of handlers on events like resize, scroll, or keyup. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment