Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait 1 second before executing AJAX request onkeyup [duplicate]

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.

like image 811
egyeneskanyar Avatar asked May 15 '14 13:05

egyeneskanyar


1 Answers

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.

like image 182
Rory McCrossan Avatar answered Oct 26 '22 22:10

Rory McCrossan