Function debounce

  • A utility for debouncing high-frequency updates. The returned value will only be updated every ms and is initially undefined, unless an initialize value is provided.

    This can be useful when a user's typing is updating a tracked property and you want to derive data less frequently than on each keystroke.

    Note that this utility requires the @use decorator (debounce could be implemented without the need for the @use decorator but the current implementation is 8 lines)

    Type Parameters

    • Value = unknown

    Parameters

    • ms: number

      delay in milliseconds to wait before updating the returned value

    • thunk: (() => Value)

      function that returns the value to debounce

        • (): Value
        • Returns Value

    • Optional initialize: Value

      value to return initially before any debounced updates

    Returns undefined | Value

    Example

     import Component from '@glimmer/component';
    import { tracked } from '@glimmer/tracking';
    import { use } from 'ember-resources';
    import { debounce } from 'reactiveweb/debounce';

    const delay = 100; // ms

    class Demo extends Component {
    @tracked userInput = '';

    @use debouncedInput = debounce(delay, () => this.userInput);
    }

    Example

    This could be further composed with RemoteData

     import Component from '@glimmer/component';
    import { tracked } from '@glimmer/tracking';
    import { use } from 'ember-resources';
    import { debounce } from 'reactiveweb/debounce';
    import { RemoteData } from 'reactiveweb/remote-data';

    const delay = 100; // ms

    class Demo extends Component {
    @tracked userInput = '';

    @use debouncedInput = debounce(delay, () => this.userInput);

    @use search = RemoteData(() => `https://my.domain/search?q=${this.debouncedInput}`);
    }

    Example

    An initialize value can be provided as the starting value instead of it initially returning undefined.

     import Component from '@glimmer/component';
    import { tracked } from '@glimmer/tracking';
    import { use } from 'ember-resources';
    import { debounce } from 'reactiveweb/debounce';

    const delay = 100; // ms

    class Demo extends Component {
    @tracked userInput = 'products';

    @use debouncedInput = debounce(delay, () => this.userInput, this.userInput);
    }

Generated using TypeDoc