chore: move utils to package

This commit is contained in:
2023-02-10 17:52:50 +01:00
parent 0c829c88c5
commit 3727b6bb2b
26 changed files with 170 additions and 160 deletions

29
packages/utils/actions.ts Normal file
View File

@@ -0,0 +1,29 @@
/**
* 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))
}
}