From 481d9b23944ff5bec1ce05c809a88acedc0e4796 Mon Sep 17 00:00:00 2001 From: Joseph Schorr Date: Wed, 3 May 2017 16:00:50 -0400 Subject: [PATCH] Add debounce to search --- .../ui/search-box/search-box.component.html | 1 + .../ui/typeahead/typeahead.directive.ts | 20 ++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/static/js/directives/ui/search-box/search-box.component.html b/static/js/directives/ui/search-box/search-box.component.html index fa6b0c045..162529c52 100644 --- a/static/js/directives/ui/search-box/search-box.component.html +++ b/static/js/directives/ui/search-box/search-box.component.html @@ -49,6 +49,7 @@ (); @Output('taEntered') entered = new EventEmitter(); private itemSelected: boolean = false; + private existingTimer: Promise = null; constructor(@Inject('$element') private $element: ng.IAugmentedJQuery, @Inject('$compile') private $compile: ng.ICompileService, @Inject('$scope') private $scope: ng.IScope, - @Inject('$templateRequest') private $templateRequest: ng.ITemplateRequestService) { + @Inject('$templateRequest') private $templateRequest: ng.ITemplateRequestService, + @Inject('$timeout') private $timeout: ng.ITimeoutService) { } public ngAfterContentInit(): void { @@ -52,12 +55,23 @@ export class TypeaheadDirective implements AfterContentInit { templates: templates, display: this.displayKey, source: (query, results, asyncResults) => { - this.typeahead.emit({'query': query, 'callback': asyncResults}); - this.itemSelected = false; + this.debounceQuery(query, asyncResults); }, }); } + private debounceQuery(query: string, asyncResults: Function): void { + if (this.existingTimer) { + this.$timeout.cancel(this.existingTimer); + this.existingTimer = null; + } + + this.existingTimer = this.$timeout(() => { + this.typeahead.emit({'query': query, 'callback': asyncResults}); + this.itemSelected = false; + }, this.debounce); + } + @HostListener('keyup', ['$event']) public onKeyup(event: JQueryKeyEventObject): void { if (!this.itemSelected && event.keyCode == 13) {