Skip to content

Instantly share code, notes, and snippets.

@plugn
Created June 4, 2026 21:14
Show Gist options
  • Select an option

  • Save plugn/32a74492efcbb7448a4d9161b2234b30 to your computer and use it in GitHub Desktop.

Select an option

Save plugn/32a74492efcbb7448a4d9161b2234b30 to your computer and use it in GitHub Desktop.
throttle & debounce from scratch
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