chore: move utils to package
This commit is contained in:
29
packages/utils/actions.ts
Normal file
29
packages/utils/actions.ts
Normal 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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user