Created
June 4, 2026 21:14
-
-
Save plugn/32a74492efcbb7448a4d9161b2234b30 to your computer and use it in GitHub Desktop.
throttle & debounce from scratch
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
| function throttle(fn, delay) { | |
| let startTime = 0 | |
| return function (...args) { | |
| const now = Date.now() | |
| // if not in progress | |
| if (startTime === 0) { | |
| startTime = now | |
| } | |
| if (now - startTime >= delay) { | |
| startTime = 0 | |
| return fn(...args) | |
| } | |
| } | |
| } | |
| function debounce(fn, delay) { | |
| let storedArgs = [] | |
| let timerId = 0 | |
| return function(...args) { | |
| storedArgs = args | |
| if (timerId) { | |
| clearTimeout(timerId) | |
| } | |
| timerId = setTimeout(later, delay) | |
| function later() { | |
| timerId = 0 | |
| return fn(...storedArgs) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment