瀏覽代碼

Merge pull request #25 from ColinEspinas/search-debounce

Added debounce on search input
Daoud Clarke 3 年之前
父節點
當前提交
02bcef640c
共有 1 個文件被更改,包括 11 次插入2 次删除
  1. 11 2
      mwmbl/tinysearchengine/static/index.js

+ 11 - 2
mwmbl/tinysearchengine/static/index.js

@@ -10,7 +10,7 @@ window.onload = (event) => {
     const length = searchInput.value.length;
     const length = searchInput.value.length;
     searchInput.setSelectionRange(length, length);
     searchInput.setSelectionRange(length, length);
 
 
-    searchInput.oninput = e => {
+    searchInput.oninput = debounce(e => {
         console.log("Key", e.key);
         console.log("Key", e.key);
         console.log(searchInput.value);
         console.log(searchInput.value);
 
 
@@ -27,7 +27,7 @@ window.onload = (event) => {
                 ts.numItems = content.length;
                 ts.numItems = content.length;
             });
             });
         });
         });
-    };
+    });
 
 
     // Handle moving the selected item up and down
     // Handle moving the selected item up and down
     document.addEventListener('keydown', (e) => {
     document.addEventListener('keydown', (e) => {
@@ -57,6 +57,15 @@ window.onload = (event) => {
 };
 };
 
 
 
 
+function debounce(callback, timeout = 100){
+    let timer;
+    return (...args) => {
+        clearTimeout(timer);
+        timer = setTimeout(() => { callback.apply(this, args); }, timeout);
+    };
+}
+
+
 function selectNextItem() {
 function selectNextItem() {
     if (ts.selected === null) {
     if (ts.selected === null) {
         ts.selected = 0;
         ts.selected = 0;