import { Observable as ObservableT } from './index' import Observable from './observable' /** * Creates an observable whos emits are debounced. * * {@link debounce} takes a `duration` of milliseconds, and an `Observable`. Any values the source `Observable` * emits will not be emitted on the output `Observable` until the duration has passed. If the source `Observable` * emits multiple values during one `duration`, then older values are discarded - in other words the output * `Observable` will only emit at-most-once per duration, with the latest value from the source `Observable`. * * @example Marble diagram for a debounce of 200 ms * * // source: |--1-2-3-----4-5------6-------7----| * // debounce(200): |---------3-------5-----6-------7--| * * @param {ObservableT} source source observable that will be debounced * @param {number} duration number of milliseconds it should be debounced * @returns {ObservableT} observable that debounces source emits by duration ms */ export default function debounce( source: ObservableT, duration: number ): ObservableT { return new Observable( ({ complete, error, next }): void => { let timer: number source.subscribe({ error, complete: (): NodeJS.Timeout | number => setTimeout(complete, duration), next: (value): void => { clearTimeout(timer) timer = (setTimeout(next, duration, value) as unknown) as number } }) } ) }