11

I have an input field, and it has a keyup event:

$(document).ready(function() {
    $('#SearchInputBox').keyup(function() {
        DoSearch($(this).val());
    });
});

How can I add a delay time, so that only when the user stopped typing for 1 second, then it will run the DoSearch function. I don't want to keep running it every time the user types a key because if they type fast, then it will lag.

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

17

Basically, set a timeout on each keyup. If there's already a timeout running, clear it and set another. The DoSearch() function will only run when the timeout is allowed to complete without being reset by another keyup (i.e., when the user has stopped typing for 1000ms).

var timeout = null;
$('#SearchInputBox').on('keyup', function () {
    var that = this;
    if (timeout !== null) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function () {
        DoSearch($(that).val());
    }, 1000);
});
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • @omega, apologies, I was focused on firing the event after the timeout that I didn't pay attention to the value you were passing. Of course `$(this)` didn't work, because it is in a different function scope. Please see my current edit. Thanks. – Derek Henderson Jun 10 '13 at 17:32