Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a jQuery delay on autocomplete

I'm trying to create a jQuery autocomplete for an application:

$("#search-input").on('keyup', function() {
    search = $(this).val();
    autocomplete_div = $(".autocomplete")
    $.get('/ajax/search/', {'search': search,}, function(response){
        autocomplete_div.html(response)
    });
});

What would I need to add to the above code to add a 400ms delay?

like image 985
David542 Avatar asked Feb 05 '26 02:02

David542


2 Answers

Use

setTimeout(function() {
    // your code here
}, 400);

setTimeout is a method provided by the browser's window object.

A more complete example that cancels a timer if already set using clearTimeout would be:

var myTimer = 0;

$("#search-input").on('keydown', function() {
    search = $(this).val();

    // cancel any previously-set timer
    if (myTimer) {
        clearTimeout(myTimer);
    }

    myTimer = setTimeout(function() {
        autocomplete_div = $(".autocomplete")
        $.get('/ajax/search/', {'search': search,}, function(response){
            autocomplete_div.html(response)
        });
    }, 400);
});

Also note use of on instead of the deprecated live.

like image 56
Duncan Smart Avatar answered Feb 07 '26 16:02

Duncan Smart


Your code should look like this: (for jQuery 1.7+)

$(document).on('keyup', "#search-input", function () {
    clearTimeout($(this).data('timeout'));
    var _self = this;
    $(this).data('timeout', setTimeout(function () {
        $.get('/ajax/search/', {
            search: _self.value
        }, function (response) {
            $(".autocomplete").html(response);
        });
    }, 400));
});

If using older jQuery version, use live() or better delegate(). BTW, you should bind it to closest static container, not document.

like image 30
A. Wolff Avatar answered Feb 07 '26 14:02

A. Wolff