Last active
December 18, 2025 08:35
-
-
Save eypsilon/6a3aad2c56c4d2291bf70cd9bbc77b4a to your computer and use it in GitHub Desktop.
Debounce and throttle, the AI way.
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 its execution | |
| * until after `wait` milliseconds have elapsed since the last time it was called | |
| * | |
| * @param {Function} func - The function to debounce | |
| * @param {number} wait - The number of milliseconds to delay | |
| * @returns {Function} A debounced version of the function | |
| * @example | |
| * // Create debounced resize handler | |
| * this.debouncedResize = this.debounce(() => { | |
| * // Handle resize | |
| * }, 150); | |
| * | |
| * // Usage: | |
| * window.addEventListener('resize', this.debouncedResize); | |
| */ | |
| function debounce(func, wait) { | |
| let timeout; | |
| return function executedFunction(...args) { | |
| if (timeout) { | |
| clearTimeout(timeout); | |
| } | |
| timeout = setTimeout(() => { | |
| func.apply(this, args); | |
| timeout = null; | |
| }, wait); | |
| }; | |
| } | |
| /** | |
| * Creates a throttled version of a function that limits its execution | |
| * to at most once every `limit` milliseconds | |
| * | |
| * @param {Function} func - The function to throttle | |
| * @param {number} limit - The number of milliseconds to wait between executions | |
| * @returns {Function} A throttled version of the function | |
| * @example | |
| * // Create throttled scroll handler | |
| * this.throttledScroll = this.throttle(() => { | |
| * // Handle scroll | |
| * }, 100); | |
| * | |
| * // Usage: | |
| * window.addEventListener('scroll', this.throttledScroll); | |
| */ | |
| function throttle(func, limit) { | |
| let lastFunc; | |
| let lastRan; | |
| return function (...args) { | |
| if (!lastRan) { | |
| func.apply(this, args); | |
| lastRan = Date.now(); | |
| } else { | |
| clearTimeout(lastFunc); | |
| lastFunc = setTimeout(() => { | |
| if ((Date.now() - lastRan) >= limit) { | |
| func.apply(this, args); | |
| lastRan = Date.now(); | |
| } | |
| }, limit - (Date.now() - lastRan)); | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment