From feaee52376430463aa53c66c4d5f87250a519714 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?King=20K=C3=A9vin?= Date: Sun, 26 Feb 2023 12:11:57 +0100 Subject: [PATCH] js: better handle multiple queries --- public/partdb.js | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/public/partdb.js b/public/partdb.js index 7fdc3f4..46f3f1f 100644 --- a/public/partdb.js +++ b/public/partdb.js @@ -6,6 +6,7 @@ // the last search query var last_search = null; +var next_search = null; // the collection of parts var parts = null; // last selected part @@ -21,23 +22,35 @@ function search() { const terms = document.getElementById('terms'); if (terms && terms.value && terms.value.length >= 3) { - } else { - return; + const current_search = '/search?terms=' + terms.value; + do_search(current_search); } +} - last_search = '/search?terms=' + terms.value; - let xhr = new XMLHttpRequest(); - xhr.open('GET', last_search, true); - xhr.onload = function() { - if (decodeURI(this.responseURL).endsWith(last_search)) { - parts = JSON.parse(this.response); - results(); - } - }; - xhr.onerror = function() { - console.log("search call failed"); - }; - xhr.send(); +function do_search(current_search) +{ + if (null == last_search) { // no request running + last_search = current_search; + let xhr = new XMLHttpRequest(); + xhr.open('GET', last_search, true); + xhr.onload = function() { + if (decodeURI(this.responseURL).endsWith(last_search)) { + parts = JSON.parse(this.response); + results(); + } + last_search = null; + if (next_search) { + do_search(next_search); + next_search = null; + } + }; + xhr.onerror = function() { + console.log("search call failed"); + }; + xhr.send(); + } else { + next_search = current_search; // save for next search + } } function results()