Skip to content

Commit

Permalink
feat(search): add debounce on autocompletion (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
azarz authored Dec 30, 2024
1 parent cc1bfea commit 9eecfb9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/js/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Globals from "./globals";
import DOM from "./dom";
import Location from "./services/location";

import jsUtils from "./utils/js-utils";

/**
* Barre de recherche et géocodage
*/
Expand Down Expand Up @@ -52,7 +54,7 @@ class Search {
clearSearch: "clearSearch"
};

document.getElementById(id.searchInput).addEventListener("keyup", (event) => {
document.getElementById(id.searchInput).addEventListener("keyup", jsUtils.debounce( (event) => {
if (event.key === "Enter" || event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
Expand All @@ -65,13 +67,13 @@ class Search {
} else {
this.#suggestAndDisplay();
}
});
}, 300));

document.getElementById(id.searchInput).addEventListener("textInput", () => {
document.getElementById(id.searchInput).addEventListener("textInput", jsUtils.debounce(() => {
setTimeout( () => {
this.#suggestAndDisplay();
}, 100);
});
}, 300));

document.getElementById(id.searchInput).addEventListener("click", () => {
DOM.$resultDiv.hidden = true;
Expand Down
26 changes: 26 additions & 0 deletions src/js/utils/js-utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright (c) Institut national de l'information géographique et forestière
*
* This program and the accompanying materials are made available under the terms of the GPL License, Version 3.0.
*/

/**
* Fonctions utilitaires
*/
let jsUtils = {
// see https://grafikart.fr/tutoriels/debounce-throttle-642
debounce(callback, delay) {
var timer;
return function() {
console.log(delay);
var args = arguments;
var context = this;
clearTimeout(timer);
timer = setTimeout( function(){
callback.apply(context, args);
}, delay);
};
}
};

export default jsUtils;

0 comments on commit 9eecfb9

Please sign in to comment.