Skip to content

Commit

Permalink
feat: add effect batching support
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed May 2, 2024
1 parent a3ae5d2 commit 98b2e1b
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/signals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,22 @@ export function createSignal<T>(
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;
}
Expand All @@ -60,3 +69,16 @@ export function createMemo<T>(cb: () => T): () => T {
// We initialize the signal with `null` to avoid calculating the value twice unnecessarily.
return value as () => T;
}

function debounce<Args extends unknown[]>(
fn: (...args: Args) => unknown,
ms = 0,
) {
let timeout: number;

return (...args: Args) => {
clearTimeout(timeout);

timeout = setTimeout(() => fn(...args), ms);
};
}

0 comments on commit 98b2e1b

Please # to comment.