I want my serach function when user stop typing, because when typing the search is being performed for each charecter. For that issue search is taking so much time. So I want when user stop typing then search function will start. My current search code:
function search(){
var searchKey = $('#search').val();
if(searchKey.length > 3){
$('body').addClass("typed-search-box-shown");
$('.typed-search-box').removeClass('d-none');
$('.search-preloader').removeClass('d-none');
$.post('{{ route('search.ajax') }}', { _token: AIZ.data.csrf, search:searchKey}, function(data){
if(data == '0'){
// $('.typed-search-box').addClass('d-none');
$('#search-content').html(null);
$('.typed-search-box .search-nothing').removeClass('d-none').html('Sorry, nothing found for <strong>"'+searchKey+'"</strong>');
$('.search-preloader').addClass('d-none');
}
else{
$('.typed-search-box .search-nothing').addClass('d-none').html(null);
$('#search-content').html(data);
$('.search-preloader').addClass('d-none');
}
});
}
else {
$('.typed-search-box').addClass('d-none');
$('body').removeClass("typed-search-box-shown");
}
}
Here's a debounced (and rewritten, with jQuery objects cached, async/await instead of a callback function, etc.) version of your search function.
Basically on keyUp you call searchDebounced(), which will then call the actual search() 500ms later, unless a new key is pressed, which resets the timeout and waits an additional 500ms :
const $search = $('#search'),
$searchContent = $('#search-content'),
$body = $("body"),
$typedSearchBox = $('.typed-search-box'),
$searchPreloader = $('.search-preloader'),
$searchNothing = $('.typed-search-box .search-nothing');
let debounceTimeout = null
function searchDebounced() {
const searchKey = $search.val().trim();
if (searchKey.length < 4) {
$typedSearchBox.addClass('d-none');
$body.removeClass("typed-search-box-shown");
return;
}
// These two lines do the debouncing work
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout( search, 500 );
}
async function search() {
$body.addClass("typed-search-box-shown");
$typedSearchBox.removeClass('d-none');
$searchPreloader.removeClass('d-none');
const data = await $.post('{{ route(' + search.ajax + ') }}', { // No idea what this route is, I'm assuming it makes sense somehow
_token: AIZ.data.csrf,
search: searchKey
})
if (data == '0') {
$searchContent.html(null);
$searchNothing.removeClass('d-none').html('Sorry, nothing found for <strong>"' + searchKey + '"</strong>');
} else {
$searchContent.html(data);
$searchNothing.addClass('d-none').html(null);
}
$searchPreloader.addClass('d-none');
}