javascript - JS - Set delay between sending AJAX request -
i working on building search feature site. have search bar sends ajax request server each time user types something. server in turn send items match search.
the problem if user types "a" , "b" send is:
a
ab
to counter have found settimeout
delays when user enters search; however, delaying when strings fire (i.e. waits 0.75 seconds before sending a
, waits 0.75 seconds before sending ab
).
here's js:
$('#searchbox').keyup(function(e) { var timeoutid = settimeout(searchrequest, 750, $(e.currenttarget).val()); }); function searchrequest(str) { if (str.length > 0) { console.log('search request initalized | sending: ', str); var xhttp = new xmlhttprequest(); xhttp.open('post', 'code send here', true); xhttp.send(str); } }
i think need debounce function.
here's basic javascript debounce function (as taken underscore.js):
// returns function, that, long continues invoked, not // triggered. function called after stops being called // n milliseconds. if `immediate` passed, trigger function on // leading edge, instead of trailing. function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callnow = immediate && !timeout; cleartimeout(timeout); timeout = settimeout(later, wait); if (callnow) func.apply(context, args); }; };
you can use debounce click:
$('#searchbox').keyup(debounce(function(e) { searchrequest$(e.currenttarget).val()); }, 750));
Comments
Post a Comment