I've got an ajax request that executes every time an user presses some button (writes text) in a certain textarea. This would work great already (it is a search filtering function btw.), but it would n't be a good idea to execute the filter after each keystroke. So I was thinking about making a delayer thing. So the ajax request would only execute only when at least 1 second has passed since the user pressed the last button. How can I achieve this?
<textarea id="text" name="text" onkeyup="Search()"</textarea>
function Search()
{
$.ajax({...
...
}
So obviously it will run all the time. For example if I type "hello" into the textarea fast it will run 5 times and it has no use. It would be enough to run it only when I stopped writing for more than 1 second.
You can use setTimeout
to delay an action for a set number of milliseconds. You can also clear the timeout to prevent requests being queued up if someone types quickly. Try this:
var timer;
function Search() {
clearTimeout(timer) // clear the request from the previous event
timer = setTimeout(function() {
$.ajax({
// ...
});
}, 200);
}
Note I made the delay 200ms which is normally more than enough time for someone to have typed several keys, but quick enough that it would not appear too slow for the UI to update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With