Search code examples
javascriptjquerydelay

jQuery keyup Delay


Hopefully this is a quick and easy one for someone to figure out. I am fairly new to using a lot of javascript/jquery, and I have the following setup to pull a customer name out of a database and display it as the user has finished typing the customer ID.

All works great, but it searches at each keyup. I know I could change it to blur but I want it to search as they go, at a delay.

Here is the current code:

function postData(){
    var id = $('#id').val();

    $.post('inc/repairs/events-backend.php',{id:id},   
        function(data){
        $("#display_customer").html(data);
    });
    return false;
}

$(function() {
    $("#id").bind('keyup',function() {postData()});
});

As you can see it is binding to each keyup which means that if you search too quick, it may leave you with the wrong result as it was still being loaded. (ie if no matches are found, it displays an error, and typing fast enough leaves the user needing to backspace and retype the last number)

Could someone assist in adding a delay to the existing code, and if possible a small explaination as to the change you made, I rather not just copy and paste without understanding.

---- EDIT ----

This is the code I finished up with, thank you guys!

function postData(){
    var id = $('#id').val();

    $.post('inc/repairs/events-backend.php',{id:id},   
        function(data){
        $("#display_customer").html(data);
    });
    return false;
}

$(function() {
    var timer;
    $("#id").bind('keyup input',function() {
        timer && clearTimeout(timer);
        timer = setTimeout(postData, 300);
    });
});

Solution

  • You should look into the setTimeout and clearTimeout functions:

    $(function() {
        var timer;
        $("#id").on('keyup',function() {
            timer && clearTimeout(timer);
            timer = setTimeout(postData, 300);
        });
    });
    

    Basically what we're doing is that instead of firing the postData function immediately, we're passing it to setTimeout, so that it fires after a given amount of time (in this case, 300 milliseconds).

    The setTimeout function returns a timer ID, which we can then pass to clearTimeout to cancel that call from ever running. On every keypress, before we set a new timer, we first check if there's a timer set. If there is, we cancel the old timer before starting a new one.


    To further enhance this, you can also abort your AJAX call on every keypress, just in case the user typed something after 300+ milliseconds (after the timer fires, but before the AJAX request returned).


    P.S. You should check out Ben Alman's throttle/debounce plugin, which would work perfectly here.