my-swiss-knife: - v1.9.9
    Preparing search index...

    Function withCallAfter

    • Creates a function that will call the provided callback only after it has been invoked a specified number of times. Optionally, you can also provide a timeout to guarantee execution after a delay.

      Useful for scenarios where an action should only happen after multiple asynchronous or user-triggered events, but should also be called after a timeout even if the condition hasn't been met.

      Parameters

      • callback: (...args: unknown[]) => void

        The function to be executed.

      • times: number = 1

        The number of times the returned function must be called before executing the callback. Defaults to 1.

      • Optionaltimeout: number

        Optional timeout in milliseconds after which the callback will be executed regardless of the call count.

      Returns (...args: unknown[]) => void

      A function that should be called repeatedly. Once the specified number of calls is reached, or the timeout is exceeded, the callback will be invoked.

      const fire = () => console.log('Fired!');
      const fn = withCallAfter(fire, 3);

      fn(); // nothing
      fn(); // nothing
      fn(); // "Fired!" — executed after 3rd call
      const fire = () => console.log('Fired!');
      const fn = withCallAfter(fire, 5, 2000);

      fn(); // if called less than 5 times in 2 seconds, still fires after timeout
      export const withCallAfter = (
      callback: (...args: unknown[]) => void,
      times: number = 1,
      timeout?: number
      ): (...args: unknown[]) => void => {
      let count = 0
      let t: NodeJS.Timeout | undefined
      let lastArgs: unknown[] = [];

      if (timeout !== undefined) {
      t = setTimeout(() => {
      t = undefined
      callback.apply(undefined, lastArgs)
      }, timeout)
      }

      return (...args: unknown[]) => {
      count++
      lastArgs = args
      if (count >= times) {
      if (t) {
      clearTimeout(t);
      t = undefined;
      }
      callback.apply(this, args)
      }
      }
      }