diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a31369f9..cc178200 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -8,6 +8,7 @@ export * from './utils/peer-utils' export * from './utils/tl-json' export * from './utils/async-lock' export * from './utils/lru-map' +export * from './utils/function-utils' export { BinaryReader } from './utils/binary/binary-reader' export { BinaryWriter } from './utils/binary/binary-writer' diff --git a/packages/core/src/utils/function-utils.ts b/packages/core/src/utils/function-utils.ts index 61eec456..7889b5fa 100644 --- a/packages/core/src/utils/function-utils.ts +++ b/packages/core/src/utils/function-utils.ts @@ -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( func: T, delay: number @@ -16,3 +27,32 @@ export function debounce( timeout = setTimeout(later, delay) } 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 (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 +}