I have a working ajax call that I've made which sends a value to an endpoint for every input change. SO if the user is typing, it sends the call per keystroke.
I put a setTimeout around it for 2 seconds, which delays the call just fine. But the problem is it still sends a call for every keystroke.
I want to get it to where, after 2 seconds, it sends a call for what's been typed so far. If the user starts typing again maybe it would set again.
I"m just trying to send fewer keystrokes and make it to where when the user stops typing there's just a slight delay and call.
Here's the call now:
$('#input').on('input', function() {
let _this = $(this);
if (_this.val() === '') {
return;
} else {
const searchResult = $(this).val();
console.log(searchResult);
//if I type "PLANT" the console shows "P" "PL" "PLA" "PLAN" "PLANT"
//after 2 seconds, send searchResult via ajax
setTimeout(function () {
$.ajax({ url: '/endpoint',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: successHandler
});
}, 2000);
}
});