Skip to content

Commit

Permalink
Merge pull request #79 from yarastqt/yarastqt.perf-watcher
Browse files Browse the repository at this point in the history
Replace throttle to debounce for watcher cb
  • Loading branch information
yarastqt committed Aug 23, 2020
2 parents 2b27c80 + db3592c commit e2823eb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
4 changes: 2 additions & 2 deletions src/cli/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
27 changes: 11 additions & 16 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,19 @@ export function isAlias(value: string | number): boolean {
return /^{.+}$/.test(String(value))
}

export function throttle<T extends []>(
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<F extends (...args: any[]) => any>(func: F, waitFor: number) {
let timeout: ReturnType<typeof setTimeout> | null = null

const debounced = (...args: Parameters<F>) => {
if (timeout !== null) {
clearTimeout(timeout)
timeout = null
}
timeout = setTimeout(() => func(...args), waitFor)
}

return debounced as (...args: Parameters<F>) => ReturnType<F>
}

type ArrayType<T> = T extends (infer U)[] ? U : never
Expand Down

0 comments on commit e2823eb

Please sign in to comment.