From 85d6324cdea289171bc23efe3944e6304e2ec3c4 Mon Sep 17 00:00:00 2001 From: Dominic Monroe Date: Fri, 14 May 2021 14:02:56 +0100 Subject: [PATCH] Add debounce to search This makes the UI feel far less laggy while typing in a search query. It avoids applying redundant searches, which can easily add up to ~150ms per character on an older device or mobile phone. --- js/main.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/js/main.js b/js/main.js index 2a69e6c..970cffc 100644 --- a/js/main.js +++ b/js/main.js @@ -3,8 +3,15 @@ $('#project-list'). css({visibility: 'visible'}); $('footer').css({visibility: 'visible'}); -$('#search-query').on('change keyup paste input', function(event) { - var query = $.trim(event.target.value.toLowerCase()); +function debounce(f, wait){ + var timeout; + return function(...args) { + clearTimeout(timeout); + timeout = setTimeout(() => f(...args), wait) + }; +}; + +function filterProjectsBySearch(query){ var projects = $('#project-list li'); if (query == '') { projects.show(); @@ -13,6 +20,13 @@ $('#search-query').on('change keyup paste input', function(event) { } $('#project-list .category').show().not(':has(li:visible)').hide(); $('#project-list').masonry('layout'); +} + +var debouncedSearch = debounce(filterProjectsBySearch, 100); + +$('#search-query').on('change keyup paste input', function(event) { + var query = $.trim(event.target.value.toLowerCase()); + debouncedSearch(query) }); $('#search-query').focus().change();