I'm trying to get products when user done with typing. But when user done typing, method runs multiple times not once.
If user type "apple" fetchProducts
method run five times and send 5 ajax request. How can I reduce at once (unless you user start to search different product)
$(document).on("keyup keydown", 'input.select2-search__field', function (e) {
let timer,
interval = 2000,
searchText = this.value;
if (e.type == "keyup") {
clearTimeout(timer);
timer = setTimeout(fetchProducts, interval);
}
if (e.type == "keydown") {
clearTimeout(timer);
}
function fetchProducts() {
$.ajax({
url: "../../../products/get-by-select-search",
type: "post",
dataType: "json",
headers: {
"X-CSRF-TOKEN": $("meta[name=csrf-token]").attr("content")
},
data: {search: searchText},
success: function (response) {
product.find('option').remove();
product.select2({
theme: "classic",
data: response
})
.val(null)
.trigger("change");
}
});
}
});