Skip to content

Debounce

Executes a function after a certain amount of time has passed.

๐ŸŽฌ Usage

<script>
    import {debounce} from "@sveu/shared"
    const sum_debounce = debounce(() => {
        alert(7 + 7)
    }, 1)
</script>

<button on:click={sum_debounce}>Sum</button>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
fn Function to execute Function Yes
s Time to wait before executing fn in second number Yes

๐Ÿ™ˆ Options

Name Description Type Default
max_wait Maximum time to wait before executing fn in second number undefined
reject_on_cancel Reject the promise if the function is cancelled boolean false

โ†ฉ๏ธ Returns

A function that executes fn after s seconds.

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { create_filter_wrapper, debounce_filter } from "../utils"
import type { DebounceFilterOptions, FunctionArgs } from "../utils"

/**
 * Debounce execution of a function.
 *
 * @param fn - A function to be executed after delay seconds debounced.
 *
 * @param s - The time to wait before invoking the function in seconds.
 *
 * @returns A new debounce function.
 */
export function debounce<T extends FunctionArgs>(
    fn: T,
    s = 0.2,
    options: DebounceFilterOptions = {}
): T {
    return create_filter_wrapper(debounce_filter(s, options), fn)
}

Last update: 2023-02-09