diff --git a/src/js/search.js b/src/js/search.js index 43ce06ac..ded98534 100644 --- a/src/js/search.js +++ b/src/js/search.js @@ -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 */ @@ -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(); @@ -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; diff --git a/src/js/utils/js-utils.js b/src/js/utils/js-utils.js new file mode 100644 index 00000000..eb7aba54 --- /dev/null +++ b/src/js/utils/js-utils.js @@ -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;