logo

debounce

The debounce function is used to prevent a function from being called too many times in a short period. The function will only be called after it stops being called for the specified amount of time.

Use normally

When calling debounce with only the function and the time, the function will be used as the key.

The function passed to the debounce function must be constant, otherwise the debounce will not work.

import { debounce } from '@aracna/core';

function fn() {
  console.log('fn ran', Date.now());
}

// will be ignored
debounce(fn, 1000);

// will be ignored
debounce(fn, 1000);

// will run after 1s
debounce(fn, 1000);

setTimeout(() => {
  // will run after 2s
  debounce(fn, 1000);
}, 2000);

Use with a custom key

The debounce function can also be called with a custom key. This is useful when you want to debounce a function that is not constant.

import { debounce } from '@aracna/core';

const key = 'dfn';

// will be ignored
debounce(() => console.log('fn1 ran', Date.now()), 1000, key);

// will be ignored
debounce(() => console.log('fn2 ran', Date.now()), 1000, key);

// will run after 1s
debounce(() => console.log('fn3 ran', Date.now()), 1000, key);

setTimeout(() => {
  // will run after 2s
  debounce(() => console.log('fn4 ran', Date.now()), 1000, key);
}, 2000);