Javascript: Timeout on a Textbox using jQuery

Here is a quick post about how to use a JavaScript-timer to only execute a textbox's functionality after a certain amount of time.

jQuery

Worth noticing in the code is that we handle a key-press on the Enter-button instantly, while otherwise we only execute the functionality after the user left the keyboard alone for 0,5 seconds.

var filterTimeoutId = 0;

var textboxFunction = function() {
   // The function the textbox should perform
};

$('input#TextBox').keypress(function (e) {
    if (e.which === 13) { // Enter-key
        e.preventDefault(); // Prevent page postback
        clearTimeout(filterTimeoutId);

        textboxFunction();
        return;
    }

    clearTimeout(filterTimeoutId);
    var timeout = 500; // Timeout in milliseconds
    filterTimeoutId = setTimeout(textboxFunction, timeout);
});

Comments