logo

throttle

The throttle function is used to prevent a function from being called too many times in a short period. The function will only be called if the time since the last call is greater than or equal to the specified amount of time.

Use normally

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

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

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

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

// will run
throttle(fn, 1000);

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

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

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

Use a custom key

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

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

const key = 'dfn';

// will run
throttle(() => console.log('fn1 ran', Date.now()), 1000, key);

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

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

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