Skip to content

Instantly share code, notes, and snippets.

@EvAlex
Last active July 20, 2017 20:25
Show Gist options
  • Save EvAlex/dc3af368c0e28a8a3eb9cb00a10b267d to your computer and use it in GitHub Desktop.
Save EvAlex/dc3af368c0e28a8a3eb9cb00a10b267d to your computer and use it in GitHub Desktop.
EventDebounvcer for Angular
import { Renderer2, NgZone } from '@angular/core';
import { Subject } from 'rxjs/Subject';
export class EventDebouncer {
constructor(private _zone: NgZone, private _renderer: Renderer2) {
}
listen(
target: 'window' | 'document' | 'body' | any,
eventName: string,
listener: (event: any) => boolean | void,
debounceTime: number = 40
): () => void {
return this._zone.runOutsideAngular(() => {
const tempSubj = new Subject<Event>();
const result = this._renderer.listen(target, eventName, (e: MouseEvent) => {
tempSubj.next(e);
e.preventDefault();
e.stopPropagation();
});
tempSubj.debounceTime(debounceTime).subscribe(e => this._zone.run(() => listener(e)));
return result;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment