Skip to content

Commit

Permalink
Fix input search lag via debounced keyup function (#3491)
Browse files Browse the repository at this point in the history
* Create debounce function, switch jets to manual search mode, debounce .keyup on the input box

* Edit comment
  • Loading branch information
dmmulroy authored and Carlgo11 committed Oct 24, 2018
1 parent 2e83883 commit 3828004
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ $(window).resize(function () {

var isSearching = false;
var jets = new Jets({
searchTag: '#jets-search',
callSearchManually: true,
contentTag: '.jets-content',
didSearch: function (searchPhrase) {
document.location.hash = '';
Expand Down Expand Up @@ -78,6 +78,14 @@ var jets = new Jets({
}
});

// Wrap the jets.search function with a debounced function
var debouncedSearch = debounce(function(e) {
jets.search(e.target.value);
}, 350);

// Attach a keyup event listener to the input
$('#jets-search').keyup(debouncedSearch);

/**
* Ensure searching is conducted with regard to the user's viewport
* after re-sizing the screen and close all categories after re-sizing
Expand Down Expand Up @@ -139,3 +147,27 @@ function closeCategory(category) {
$('.' + category + '-table').css('display', 'none');
document.location.hash = '';
}

/**
* 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.
*
* @param func The function to be debounced
* @param wait The time in ms to debounce
*/
function debounce(func, wait) {
var timeout;

return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};

clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (!timeout) func.apply(context, args);
};
};

0 comments on commit 3828004

Please sign in to comment.