I have the following code block that sends the contents of a text input with id searchBox
to a server using jQuery.
$(document).ready(function () {
$('#searchBox').on('input', function () {
var searchContent = $(this).val()
if (searchContent.length == 0) {
// other not relevant code
}
else {
$.post('/checkAvailability',
{ domainName: searchContent },
function (data, status, jqXHR) {
console.log(status ' ' data);
});
}
});
});
How can I call the $.post
function only if the search content has not changed for 3 seconds?
CodePudding user response:
Without using another implementation like lodash.throttle
or lodash.debounce
, you could use setTimeout
and clearTimeout
.
(I commented out the call to $.post
and just used a console.log()
call for the demo)
$(document).ready(function() {
let run;
$("#searchBox").on("input", function() {
const searchContent = $(this).val();
clearTimeout(run);
if (searchContent.length == 0) {
// other not relevant code
} else {
run = setTimeout(() => {
console.log(searchContent);
/* $.post(
"/checkAvailability", {
domainName: searchContent
},
function(data, status, jqXHR) {
console.log(status " " data);
}
); */
}, 3000);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchBox" />