From bdc9497a00b9cb9187ce090040e584183f57469c Mon Sep 17 00:00:00 2001 From: aashna27 Date: Sun, 3 Mar 2019 20:43:05 +0530 Subject: [PATCH] Added debounce for typeahead search optimization --- .eslintrc | 3 +++ app/assets/javascripts/debounce.js | 18 ++++++++++++++++++ app/assets/javascripts/restful_typeahead.js | 6 +++--- 3 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 app/assets/javascripts/debounce.js diff --git a/.eslintrc b/.eslintrc index 9faa37508e..de99afaf3e 100644 --- a/.eslintrc +++ b/.eslintrc @@ -9,6 +9,9 @@ env: jquery: true node: true +parseOptions: + sourceType: module + # http://eslint.org/docs/rules/ rules: # Possible Errors diff --git a/app/assets/javascripts/debounce.js b/app/assets/javascripts/debounce.js new file mode 100644 index 0000000000..12f2cbc7e0 --- /dev/null +++ b/app/assets/javascripts/debounce.js @@ -0,0 +1,18 @@ +// Returns a function, that, as long as it continues to be invoked, will not +// be triggered. The function will be called after it stops being called for +// N milliseconds. If `immediate` is passed, trigger the function on the +// leading edge, instead of the trailing. +export function debounce(func, wait, immediate) { + var timeout; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; +}; \ No newline at end of file diff --git a/app/assets/javascripts/restful_typeahead.js b/app/assets/javascripts/restful_typeahead.js index b4e7a0a33e..e720a65aab 100644 --- a/app/assets/javascripts/restful_typeahead.js +++ b/app/assets/javascripts/restful_typeahead.js @@ -4,13 +4,13 @@ search API and the UI components. Documentation here: https://github.com/bassjobsen/Bootstrap-3-Typeahead **/ +import { debounce } from './debounce.js'; $(function() { - $('input.search-query.typeahead').each(function(i, el){ + $('input.search-query.typeahead').each(debounce(function(i, el){ var typeahead = $(el).typeahead({ items: 10, minLength: 3, - delay: 350, showCategoryHeader: true, autoSelect: false, source: function (query, process) { @@ -46,5 +46,5 @@ $(function() { showAll: true } }); - }); + }, 350)); });