From 98b2e1b81bb202b8f9726030ed440d89c1c0dcb9 Mon Sep 17 00:00:00 2001 From: StyleShit Date: Thu, 2 May 2024 08:56:40 +0300 Subject: [PATCH] feat: add effect batching support --- src/signals.ts | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/signals.ts b/src/signals.ts index 50a0182..05ff738 100644 --- a/src/signals.ts +++ b/src/signals.ts @@ -37,13 +37,22 @@ export function createSignal( return [signal.get, signal.set]; } -export function createEffect(cb: EffectCallback) { - stack.add(cb); +type EffectOptions = { + batch: boolean; +}; + +export function createEffect( + cb: EffectCallback, + options: EffectOptions = { batch: true }, +) { + const effectFn = options.batch ? debounce(cb) : cb; + + stack.add(effectFn); try { cb(); } catch (e) { - stack.delete(cb); + stack.delete(effectFn); throw e; } @@ -60,3 +69,16 @@ export function createMemo(cb: () => T): () => T { // We initialize the signal with `null` to avoid calculating the value twice unnecessarily. return value as () => T; } + +function debounce( + fn: (...args: Args) => unknown, + ms = 0, +) { + let timeout: number; + + return (...args: Args) => { + clearTimeout(timeout); + + timeout = setTimeout(() => fn(...args), ms); + }; +}