CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

debounce

Delays function execution until a specified amount of time has passed since the last call.

debounce(fn, delay):(...args: TArgs) => void

Parameters

fn(...args: TArgs) => voidrequired

The function to execute after the delay has passed without another call.

delaynumberrequired

The delay in milliseconds before the function is executed.

Returns

(...args: TArgs) => void

A debounced function that resets its timer whenever it is called.

Examples

01

Basic usage

The function executes after the specified delay.

TypeScript
import { debounce } from "@cyref/js";

const logMessage = debounce(() => {
  console.log("Executed");
}, 500);

logMessage();
02

Resetting the delay

Calling the debounced function again clears the previous timeout and starts the delay again.

TypeScript
import { debounce } from "@cyref/js";

const search = debounce((query: string) => {
  console.log("Searching:", query);
}, 500);

search("c");
search("cy");
search("cyref");

// Only the last call is executed after 500ms.
// Searching: cyref
03

Passing arguments

Arguments passed to the debounced function are forwarded to the original function when it executes.

TypeScript
import { debounce } from "@cyref/js";

const greet = debounce((name: string) => {
  console.log(`Hello, ${name}!`);
}, 300);

greet("Amir");

// After 300ms:
// Hello, Amir!
04

Multiple arguments

The debounced function supports multiple arguments with the same types as the original function.

TypeScript
import { debounce } from "@cyref/js";

const calculate = debounce(
  (a: number, b: number) => {
    console.log(a + b);
  },
  500,
);

calculate(10, 20);

// After 500ms:
// 30
05

Repeated calls

Only the most recent call is executed when multiple calls occur before the delay expires.

TypeScript
import { debounce } from "@cyref/js";

const save = debounce((value: string) => {
  console.log("Saved:", value);
}, 1000);

save("first");

setTimeout(() => {
  save("second");
}, 300);

setTimeout(() => {
  save("third");
}, 600);

// Only "third" is executed after the final 1000ms delay.
// Saved: third
06

Useful for input events

debounce can delay frequently triggered callbacks such as input or search events.

TypeScript
import { debounce } from "@cyref/js";

const handleSearch = debounce((value: string) => {
  console.log("Search:", value);
}, 400);

handleSearch("Java");
handleSearch("JavaScript");

// Only the latest call is executed after 400ms.
// Search: JavaScript
Built with@cyref/js·Official documentation