Skip to content

Instantly share code, notes, and snippets.

@michaelneu
Created August 11, 2016 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelneu/5d0fe265e6d80e1923fbb3c9eca4d30c to your computer and use it in GitHub Desktop.
Save michaelneu/5d0fe265e6d80e1923fbb3c9eca4d30c to your computer and use it in GitHub Desktop.
Typescript implementation of a debouncer using rxjs Observable
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
import "rxjs/add/operator/debounceTime";
/**
* Class representing a debouncer to delay incoming events.
*/
export default class Debouncer<T> {
private observer: Observer<T>;
/**
* Creates a debouncer.
*
* @param {(data: T) => void} debounced The method to call when the event is debounced.
* @param {number} debounceTime The time to debounce the event.
*/
public constructor(debounced: (data: T) => void, debounceTime: number) {
let observable = new Observable<T>((observer) => {
this.observer = observer;
});
let subscription = observable.debounceTime(debounceTime).subscribe((data) => {
debounced(data);
});
}
/**
* Update the debouncer's event's value.
*
* @param {T} data The value to assign to the debouncer.
*/
public update(data: T) {
this.observer.next(data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment