Skip to content

Instantly share code, notes, and snippets.

@Bengejd
Created February 10, 2019 21:10
Show Gist options
  • Save Bengejd/eb8b361e233e1845b06ec0ce07d63b70 to your computer and use it in GitHub Desktop.
Save Bengejd/eb8b361e233e1845b06ec0ce07d63b70 to your computer and use it in GitHub Desktop.
Debounce a user input
@Pipe({name: 'debounce', pure: false})
export class DebouncePipe {
private currentValue: any = null;
private transformValue: any = null;
private timeoutHandle: number = -1;
constructor(
private changeDetector: ChangeDetectorRef,
private zone: NgZone,
) {
}
transform(value: any, debounceTime?: number): any {
if (this.currentValue == null) {
this.currentValue = value;
return value;
}
if (this.currentValue === value) {
// there is no value that needs debouncing at this point
clearTimeout(this.timeoutHandle);
return value;
}
if (this.transformValue !== value) {
// there is a new value that needs to be debounced
this.transformValue = value;
clearTimeout(this.timeoutHandle);
this.timeoutHandle = setTimeout(() => {
this.zone.run(() => {
this.currentValue = this.transformValue;
this.transformValue = null;
this.changeDetector.markForCheck();
});
}, typeof debounceTime == 'number' ? debounceTime : 500);
}
return this.currentValue;
}
}
<div
*ngIf="hasInputError(contentOption) | debounce"
class="error-message">
{{errorMessage(contentOption)}}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment