Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add useThrottle and Throttled #115

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/afraid-mangos-suffer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"runed": minor
---

New Utilities: `useThrottle` and `Throttled`
34 changes: 34 additions & 0 deletions packages/runed/src/lib/utilities/Throttled/Throttled.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useThrottle } from "../useThrottle/useThrottle.svelte.js";
import { watch } from "../watch/watch.svelte.js";
import type { Getter, MaybeGetter } from "$lib/internal/types.js";
import { noop } from "$lib/internal/utils/function.js";

export class Throttled<T> {
#current: T = $state()!;
#throttleFn: ReturnType<typeof useThrottle>;

constructor(getter: Getter<T>, wait: MaybeGetter<number> = 250) {
this.#current = getter(); // Immediately set the initial value

this.#throttleFn = useThrottle(() => {
this.#current = getter();
}, wait);

watch(getter, () => {
this.#throttleFn()?.catch(noop);
});
}

get current(): T {
return this.#current;
}

cancel() {
this.#throttleFn.cancel();
}

setImmediately(v: T) {
this.cancel();
this.#current = v;
}
}
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/Throttled/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./Throttled.svelte.js";
2 changes: 2 additions & 0 deletions packages/runed/src/lib/utilities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ export * from "./AnimationFrames/index.js";
export * from "./useIntersectionObserver/index.js";
export * from "./IsFocusWithin/index.js";
export * from "./FiniteStateMachine/index.js";
export * from "./Throttled/index.js";
export * from "./useThrottle/index.js";
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/useThrottle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useThrottle.svelte.js";
102 changes: 102 additions & 0 deletions packages/runed/src/lib/utilities/useThrottle/useThrottle.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { untrack } from "svelte";

import type { MaybeGetter } from "$lib/internal/types.js";

type UseThrottleReturn<Args extends unknown[], Return> = ((
this: unknown,
...args: Args
) => Promise<Return>) & {
cancel: () => void;
pending: boolean;
};

export function useThrottle<Args extends unknown[], Return>(
callback: (...args: Args) => Return,
interval: MaybeGetter<number> = 250
): UseThrottleReturn<Args, Return> {
let lastCall = 0;
let timeout = $state<ReturnType<typeof setTimeout> | undefined>();
let resolve: ((value: Return) => void) | null = null;
let reject: ((reason: unknown) => void) | null = null;
let promise: Promise<Return> | null = null;

function reset() {
timeout = undefined;
promise = null;
resolve = null;
reject = null;
}

function throttled(this: unknown, ...args: Args): Promise<Return> {
return untrack(() => {
const now = Date.now();
const intervalValue = typeof interval === "function" ? interval() : interval;
const nextAllowedTime = lastCall + intervalValue;

if (!promise) {
promise = new Promise<Return>((res, rej) => {
resolve = res;
reject = rej;
});
}

if (now < nextAllowedTime) {
if (!timeout) {
timeout = setTimeout(async () => {
try {
const result = await callback.apply(this, args);
resolve?.(result);
} catch (error) {
reject?.(error);
} finally {
clearTimeout(timeout);
reset();
lastCall = Date.now();
}
}, nextAllowedTime - now);
}

return promise;
}

if (timeout) {
clearTimeout(timeout);
timeout = undefined;
}
lastCall = now;
try {
const result = callback.apply(this, args);
resolve?.(result);
} catch (error) {
reject?.(error);
} finally {
reset();
}

return promise;
});
}

throttled.cancel = async () => {
if (timeout) {
if (timeout === undefined) {
// Wait one event loop to see if something triggered the throttled function
await new Promise((resolve) => setTimeout(resolve, 0));
if (timeout === undefined) return;
}

clearTimeout(timeout);
reject?.("Cancelled");
reset();
}
};

Object.defineProperty(throttled, "pending", {
enumerable: true,
get() {
return !!timeout;
},
});

return throttled as unknown as UseThrottleReturn<Args, Return>;
}
49 changes: 49 additions & 0 deletions sites/docs/content/utilities/throttled.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: Throttled
description: A wrapper over `useThrottle` that returns a throttled state.
category: State
---

<script>
import Demo from '$lib/components/demos/throttled.svelte';
</script>

## Demo

<Demo />

## Usage

This is a simple wrapper over [`useThrottle`](https://runed.dev/docs/utilities/use-throttle) that
returns a throttled state.

```svelte
<script lang="ts">
import { Throttled } from "runed";

let search = $state("");
const throttled = new Throttled(() => search, 500);
</script>

<div>
<input bind:value={search} />
<p>You searched for: <b>{throttled.current}</b></p>
</div>
```

You may cancel the pending update, or set a new value immediately. Setting immediately also cancels
any pending updates.

```ts
let count = $state(0);
const throttled = new Throttled(() => count, 500);
count = 1;
throttled.cancel();
// after a while...
console.log(throttled.current); // Still 0!

count = 2;
console.log(throttled.current); // Still 0!
throttled.setImmediately(count);
console.log(throttled.current); // 2
```
46 changes: 46 additions & 0 deletions sites/docs/content/utilities/use-throttle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
title: useThrottle
description: A higher-order function that throttles the execution of a function.
category: Utilities
---

<script>
import Demo from '$lib/components/demos/use-throttle.svelte';
</script>

## Demo

<Demo />

## Usage

```svelte
<script lang="ts">
import { useThrottle } from "runed";

import { Label } from "../ui/label";
import DemoContainer from "$lib/components/demo-container.svelte";
import Input from "$lib/components/ui/input/input.svelte";

let search = $state("");
let throttledSearch = $state("");
let durationMs = $state(1000);

const throttledUpdate = useThrottle(
() => {
throttledSearch = search;
},
() => durationMs
);

$effect(() => {
search;
throttledUpdate();
});
</script>

<div>
<input bind:value={search} />
<p>You searched for: <b>{throttledSearch}</b></p>
</div>
```
34 changes: 34 additions & 0 deletions sites/docs/src/lib/components/demos/throttled.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<script lang="ts">
import { Throttled } from "runed";

import { Label } from "../ui/label";
import DemoContainer from "$lib/components/demo-container.svelte";
import Input from "$lib/components/ui/input/input.svelte";

let search = $state("");
let durationMs = $state(1000);
const throttledSearch = new Throttled(
() => search,
() => durationMs
);
</script>

<DemoContainer class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label for="duration">Throttle duration (ms)</Label>
<Input id="duration" type="number" bind:value={durationMs} />
</div>

<div class="flex flex-col gap-1.5">
<Label for="search">Search</Label>
<Input bind:value={search} placeholder="Search the best utilities for Svelte 5" />
</div>

<p>
{#if throttledSearch.current}
You searched for: <b>{throttledSearch.current}</b>
{:else}
Search for something above!
{/if}
</p>
</DemoContainer>
43 changes: 43 additions & 0 deletions sites/docs/src/lib/components/demos/use-throttle.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<script lang="ts">
import { useThrottle } from "runed";

import { Label } from "../ui/label";
import DemoContainer from "$lib/components/demo-container.svelte";
import Input from "$lib/components/ui/input/input.svelte";

let search = $state("");
let throttledSearch = $state("");
let durationMs = $state(1000);

const setThrottledSearch = useThrottle(
() => {
throttledSearch = search;
},
() => durationMs
);

$effect(() => {
// eslint-disable-next-line no-unused-expressions
search;
setThrottledSearch();
});
</script>

<DemoContainer class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label for="duration">Throttle duration (ms)</Label>
<Input id="duration" type="number" bind:value={durationMs} />
</div>

<div class="flex flex-col gap-1.5">
<Label for="search">Search</Label>
<Input bind:value={search} placeholder="Search the best utilities for Svelte 5" />
</div>
<p>
{#if throttledSearch}
You searched for: <b>{throttledSearch}</b>
{:else}
Search for something above!
{/if}
</p>
</DemoContainer>
Loading