From 66182c6b12b08f4ff18abfdd2c0936c6f3a945c5 Mon Sep 17 00:00:00 2001 From: Eugene Date: Sun, 23 Aug 2020 22:34:29 +0300 Subject: [PATCH] perf: replace throttle to debounce for watcher cb --- src/cli/build.ts | 4 ++-- src/core/utils.ts | 27 +++++++++++---------------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/cli/build.ts b/src/cli/build.ts index 6217011..4289ad7 100644 --- a/src/cli/build.ts +++ b/src/cli/build.ts @@ -6,7 +6,7 @@ import chalk from 'chalk' import { loadConfig } from '../core/config' import { build } from '../core/build' import { loadTheme } from '../core/load-theme' -import { throttle, flatten } from '../core/utils' +import { debounce, flatten } from '../core/utils' type Flags = { config: string @@ -61,7 +61,7 @@ export default class Build extends Command { } const watcher = watch(themes, { ignoreInitial: true }) - const onChange = throttle(async () => { + const onChange = debounce(async () => { if (!isShutdown) { this.clear() await this.build(config) diff --git a/src/core/utils.ts b/src/core/utils.ts index 45bf63c..d91db35 100644 --- a/src/core/utils.ts +++ b/src/core/utils.ts @@ -19,24 +19,19 @@ export function isAlias(value: string | number): boolean { return /^{.+}$/.test(String(value)) } -export function throttle( - callback: (..._: T) => void, - delay: number, -): (..._: T) => void { - let timeout: NodeJS.Timeout | undefined - let lastArgs: T - const next = () => { - timeout = clearTimeout(timeout as any) as undefined - callback(...lastArgs) - } - - return (...args: T) => { - lastArgs = args - - if (timeout === undefined) { - timeout = setTimeout(next, delay) +// eslint-disable-next-line space-before-function-paren +export function debounce any>(func: F, waitFor: number) { + let timeout: ReturnType | null = null + + const debounced = (...args: Parameters) => { + if (timeout !== null) { + clearTimeout(timeout) + timeout = null } + timeout = setTimeout(() => func(...args), waitFor) } + + return debounced as (...args: Parameters) => ReturnType } type ArrayType = T extends (infer U)[] ? U : never