Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a wait timer on an input field keyup event?

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.

like image 966
omega Avatar asked Jun 10 '13 17:06

omega


People also ask

How do I delay a Keyup event?

There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.

How do you trigger an event in input text after quitting typing writing?

$('input#username'). keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $. post('/ajax/fetch', { type: 'username', value: _this.

What is event Keyup?

The keyup event is fired when a key is released. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .


1 Answers

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);
});
like image 117
Derek Henderson Avatar answered Oct 04 '22 01:10

Derek Henderson