@alanscodelog/utils
    Preparing search index...

    Function debounce

    • Returns a debounced function.

      Has all the typical options (e.g. trailing, leading) for a debounce function and the ability to cancel/flush the debounced funciton.


      const callback = () => {}
      const debounced = debounce(callback, 1000)

      debounced.cancel() // clear all timeouts
      debounced.flush() // if there's a pending funciton, call it then cancel

      AND it can also create debounced queues.

      Debounced Queues

      Queues allow you to avoid creating a debounce function for every instance that needs to debounce the same function.

      For example, say you want to debounce the saving of notes to a database until after a user stops typing. For each note open you would have to create a debounced version of the save function, and usually, when using frameworks, this would happen at the component level, not the store because the store save function is shared.

      Queues would allow you to avoid all that, and keep all the saving logic at the store level, allowing components to just call save normally.

      To use queues, either pass { queues: true } or { queues: {} }. You can also have multiple debounced functions share a queue (e.g. save and delete):

      const sharedQueue = {}
      const save = debounce(_save, 1000, {
      queues: sharedQueue
      })
      const remove = debounce(_remove, 1000, {
      queues: sharedQueue
      })

      Internally the queues object looks like this, where key is one of the arguments passed to the function (e.g. a note's id), by default the first, and it deletes the key after a function is finally called:

      queues: {
      [key]: {
      // ... info needed internally
      }
      }

      So the following would debounce the callback based on the id the function was called with:

      function _save(id, some, other, arguments) {
      //...
      }
      const save = debounce(_save, 1000)
      // equivalent of debounce(_save, 1000, {index: 0})

      If you need to debounce based on something more complicated (a property of an argument or multiple arguments) index can be a function that returns the key to use.

      const save = debounce(_save, 1000, {
      index: (arguments) => {
      // multiple arguments
      return arguments[0] + arguments[2]
      // some key of the arguments
      return arguments[0].someProperty
      }
      })

      Promisified Debounce

      The function also supports wrapping async by passing {promisify: true}. We must tell the function whether to promisify since we can't/shouldn't deferentiate between regular and async function.

      When promisify is enabled, when the funciton is debounced, the callback will be called with Error("Debounced") as the first param. This is so that when awaiting you can tell whether the result is a real result, or just the debounce.

      You can check what type of result it is with the isDebouncedResult utilty funciton.

      const callback = (maybeArg) => {
      // change what is returned when the funciton is debounced, if needed
      if (isDebouncedResult(maybeArg)) return maybeArg
      // do stuff
      if (!ok) throw new Error("Custom Error")
      }
      const debounced = debounce(callback, 1000, { promisify: true })
      const res = await debounced().catch(err => {
      // if needed errors from the callback can be caught here
      })

      if (!isDebouncedResult(res)) {
      // ...
      }

      Type Parameters

      Parameters

      • callback: T

        The function to debounce.

      • wait: number = 0

        How long to wait before calling the function after the last call. Defaults to 0

      • __namedParameters: {
            index?: TQueued extends true
                ? number
                | ((...args: Parameters<T>) => number)
                : undefined;
            leading?: boolean;
            promisify?: TPromisify;
            queue?: DebounceQueue | TQueued;
            trailing?: boolean;
        } = {}
        • Optionalindex?: TQueued extends true ? number | ((...args: Parameters<T>) => number) : undefined

          The index number of the argument that will be used as the key to the queues if queues are enabled.

        • Optionalleading?: boolean

          Whether the first call is called immediately, and all subsequent calls ignored, defaults to false. Note that if trailing and leading are both set to true, trailing will only fire if there were multiple calls before the wait period timed out.

        • Optionalpromisify?: TPromisify

          Whether to promisify the debounced function.

        • Optionalqueue?: DebounceQueue | TQueued

          Whether to use queues, or a queues object to use.

        • Optionaltrailing?: boolean

          Whether the call is delayed until the end of the timeout. Defaults to true.

      Returns Debounced<T, TPromisify>