Radash
  1. Curry
  2. debounce

Basic usage

Debounce accepts an options object with a delay and a source function to call when invoked. When the returned function is invoked it will only call the source function after the delay milliseconds of time has passed. Calls that don’t result in invoking the source reset the delay, pushing off the next invocation.

import { debounce } from 'radash'

const makeSearchRequest = (event) => {
  api.movies.search(event.target.value)
}

input.addEventListener('change', debounce({ delay: 100 }, makeSearchRequest))

Timming

A visual of the debounce behavior when delay is 100. The debounce function returned by debounce can be called every millisecond but it will only call the given callback after delay milliseconds have passed.

                Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - - 
debounce Invocations: x x x x - - - - - - - - x x x x x x x x x x - - - - - - - - - - - -
  Source Invocations: - - - - - - - - - - x - - - - - - - - - - - - - - - - - x - - - - -

Cancel

The function returned by debounce has a cancel property, a function that when called will permanently stop the source function from being debounced.

const debounced = debounce({ delay: 100 }, api.feed.refresh)

// ... sometime later

debounced.cancel()

Flush

The function returned by debounce has a flush property, a function that when called will directly invoke the source function.

const debounced = debounce({ delay: 100 }, api.feed.refresh)

// ... sometime later

debounced.flush(event)