debounce

repository·main·Indexed 21 days ago

https://github.com/sindresorhus/debounce

A utility that delays function calls until a specified amount of time has elapsed since the last invocation. Version 3.0.0 provides a debounced function with options for immediate execution and management methods including .isPending, .clear(), .flush(), and .trigger().

Tokens
1.7K
Snippets
7
Records
9
Agent score
73%

What's inside debounce

  1. Basic usage of debounce

    main

    Import debounce and wrap a function to delay its execution. The function will only run after wait milliseconds have passed since the last time it was called. This is useful for performance-heavy tasks like window resizing or scroll events.

    import debounce from 'debounce';
    
    function resize() {
    	console.log('height', window.innerHeight);
    	console.log('width', window.innerWidth);
    }
    
    window.onresize = debounce(resize, 200);
  2. Manage debounced function state and execution

    main

    You can interact with a debounced function instance using its built-in methods to check status or force execution:

    // Check if a delay is active
    window.onresize.isPending;
    
    // Cancel scheduled executions
    window.onresize.clear();
    
    // Execute immediately if scheduled, then clear timer
    window.onresize.flush();
    
    // Execute immediately and reset timer if it was set
    window.onresize.trigger();
  3. Control the debounced function with methods

    main

    The function returned by debounce includes several methods to manage its state and execution:

    • .isPending: A boolean indicating whether the debounce delay is currently active.
    • .clear(): Cancels any currently scheduled executions.
    • .flush(): If an execution is scheduled, it will be executed immediately and the timer will be cleared.
    • .trigger(): Executes the function immediately and clears the timer if it was previously set.
  4. Use debounce(fn, wait, options?)

    main

    Creates a debounced function that delays execution until wait milliseconds have passed since its last invocation.

    Parameters:

    • fn: The function to debounce.
    • wait: The delay in milliseconds.
    • options?: An optional configuration object. Setting { immediate: true } will execute the function immediately at the start of the wait interval (useful for preventing double-clicks on buttons).
  5. Configure debounce with immediate execution

    main

    You can pass an Options object to debounce to change its behavior. Setting immediate: true causes the function to execute immediately at the start of the wait interval. This is particularly useful for preventing issues like double-clicks on a button, as the first call executes immediately and subsequent calls within the wait period are ignored.

    import debounce from 'debounce';
    
    const saveInput = debounce(() => {
    	console.log('Saving...');
    }, 300, {immediate: true});
    
    // First call executes immediately
    // Subsequent calls within 300ms are ignored
    saveInput();
    saveInput(); // Ignored
  6. Control a debounced function with DebouncedFunction methods

    main

    The DebouncedFunction returned by debounce includes several methods to manage the execution lifecycle:

    • isPending: A boolean indicating whether a debounce delay is currently active.
    • clear(): Cancels any scheduled executions.
    • flush(): If an execution is scheduled, it will be immediately executed and the timer will be cleared.
    • trigger(): Executes the function immediately and clears the timer if it was previously set.
    import debounce from 'debounce';
    
    const fn = debounce(() => console.log('Called'), 100);
    
    // Check pending status
    fn();
    console.log(fn.isPending); // true
    
    // Cancel execution
    fn.clear();
    console.log(fn.isPending); // false
    
    // Immediate execution (flush)
    fn();
    fn.flush(); // 'Called' is logged immediately
    
    // Immediate execution (trigger)
    fn();
    fn.trigger(); // 'Called' is logged immediately
  7. Manage debounced function state with isPending, clear, flush, and trigger

    main

    The function returned by debounce includes several utility methods to manage its execution state:

    • isPending: A getter that returns true if there is a pending execution (i.e., a timeout is currently active).
    • clear(): Cancels any pending execution and clears the stored context and arguments.
    • flush(): Immediately executes the pending function if one is queued.
    • trigger(): Immediately executes the function and then clears the pending state.
    import debounce from 'debounce';
    
    const debounced = debounce(() => {
    	console.log('Executed');
    }, 1000);
    
    debounced();
    
    console.log(debounced.isPending); // true
    
    debounced.flush(); // Executes immediately
    console.log(debounced.isPending); // false
    
    debounced.clear(); // Cancels pending execution
  8. Use the debounce function

    main

    The debounce function creates a debounced version of the provided function that delays its execution until after wait milliseconds have elapsed since the last time it was invoked. This is useful for rate-limiting high-frequency events like window resizing or keystrokes.

    Parameters

    • function_: The function to debounce. Must be a function.
    • wait: The number of milliseconds to delay. Defaults to 100. Must be non-negative.
    • options: An object containing configuration. Defaults to {}.
      • immediate: If true, the debounced function will trigger the function on the leading edge instead of the trailing edge.

    Errors

    • Throws TypeError if function_ is not a function.
    • Throws TypeError if options is a boolean (use {immediate: true} instead).
    • Throws RangeError if wait is negative.
    import debounce from 'debounce';
    
    const debounced = debounce(() => {
    	console.log('Debounced function executed');
    }, 500);
    
    // Call the debounced function
    debounced();