Files
housesof/packages/utils/actions.ts

30 lines
1.0 KiB
TypeScript

/**
* Debounce a function with a given amount of time
* @description For scrolling or other resource demanding behaviors
*/
export const debounce = (callback: (...args: any[]) => any, wait: number, immediate = false) => {
let timeout: ReturnType<typeof setTimeout> | number = 0
return (...args: any[]) => {
const callNow: boolean = immediate && !timeout
const next = () => callback(...args)
clearTimeout(timeout)
timeout = setTimeout(next, wait)
if (callNow) next()
}
}
/**
* Throttle a function by a given amount of time
* @description Throttling enforces a maximum number of times a function can be called over time, as in 'execute this function at most once every 100 milliseconds
*/
export const throttle = (fn: (...args: any[]) => any, delay: number) => {
let lastCall = 0
return (...args: unknown[]) => {
const now = performance.now()
if (now - lastCall < delay) return
lastCall = now
requestAnimationFrame(() => fn(...args))
}
}