JavaScript: Delayed keypress event (sort of)

Wanted to do an AJAX call whenever the content of a field was changed. This can be done simply with the onchange event, but the problem is that you have to tab out of the field to make it fire. You can also do it with the keypress event, but then you’ll get one AJAX call for each and every keypress, which is just silly.

Found a nice and easy solution, and here it is slightly simplified.

var key_press_counter = 0;

function check(n)
{
    // Do something
    if(n == key_press_counter)
    {
        // Check field, do an ajax call, whatever
    }
}


$(function()
{
    check(0);
    $('#input').keypress(function()
    {
        setTimeout(check, 1000, ++key_press_counter);
    });
});

It’s a bit sneaky, but you should be able to deduce how it works :wink: Working sample over at samples.geekality.net/delay-check.