feat(core): exported debounce function, implemented and exported throttle function.
This commit is contained in:
parent
c228085bfe
commit
3ecef3bde4
2 changed files with 41 additions and 0 deletions
|
@ -8,6 +8,7 @@ export * from './utils/peer-utils'
|
||||||
export * from './utils/tl-json'
|
export * from './utils/tl-json'
|
||||||
export * from './utils/async-lock'
|
export * from './utils/async-lock'
|
||||||
export * from './utils/lru-map'
|
export * from './utils/lru-map'
|
||||||
|
export * from './utils/function-utils'
|
||||||
|
|
||||||
export { BinaryReader } from './utils/binary/binary-reader'
|
export { BinaryReader } from './utils/binary/binary-reader'
|
||||||
export { BinaryWriter } from './utils/binary/binary-writer'
|
export { BinaryWriter } from './utils/binary/binary-writer'
|
||||||
|
|
|
@ -1,3 +1,14 @@
|
||||||
|
/**
|
||||||
|
* Debounce a function with a given delay.
|
||||||
|
* Similar to lodash.
|
||||||
|
*
|
||||||
|
* Debouncing `F` for a delay of `D` means that
|
||||||
|
* `F` will be called after `D` passed since tha
|
||||||
|
* last time `F` was called.
|
||||||
|
*
|
||||||
|
* @param func Function to debounce
|
||||||
|
* @param delay Debounce delay
|
||||||
|
*/
|
||||||
export function debounce<T extends Function>(
|
export function debounce<T extends Function>(
|
||||||
func: T,
|
func: T,
|
||||||
delay: number
|
delay: number
|
||||||
|
@ -16,3 +27,32 @@ export function debounce<T extends Function>(
|
||||||
timeout = setTimeout(later, delay)
|
timeout = setTimeout(later, delay)
|
||||||
} as any
|
} as any
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throttle a function with a given delay.
|
||||||
|
* Similar to lodash.
|
||||||
|
*
|
||||||
|
* Throttling `F` for a delay of `D` means that
|
||||||
|
* `F` will be called no more than 1 time every `D`.
|
||||||
|
* In this implementation, `F` is called after `D`
|
||||||
|
* has passed since the previous non-throttled invocation
|
||||||
|
*
|
||||||
|
* @param func Function to throttle
|
||||||
|
* @param delay Throttle delay
|
||||||
|
*/
|
||||||
|
export function throttle<T extends Function> (func: T, delay: number): T {
|
||||||
|
let timeout: NodeJS.Timeout | null
|
||||||
|
|
||||||
|
return function (this: any) {
|
||||||
|
if (timeout) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const self = this
|
||||||
|
const args = arguments
|
||||||
|
const later = function (): void {
|
||||||
|
timeout = null
|
||||||
|
func.apply(self, args)
|
||||||
|
}
|
||||||
|
timeout = setTimeout(later, delay)
|
||||||
|
} as any
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue