How to trigger an event in input text after I stop typing/writting?

Posted by user1386320 on Stack Overflow See other posts from Stack Overflow or by user1386320
Published on 2012-12-26T14:48:11Z Indexed on 2013/11/06 9:54 UTC
Read the original article Hit count: 184

I want to trigger event just right after I stop typing (not while typing) characters in my input textbox.

I've tried with:

$('input#username').keypress(function() {
    var _this = $(this); // copy of this object for further usage

    setTimeout(function() {
        $.post('/ajax/fetch', {
            type: 'username',
            value: _this.val()
        }, function(data) {
            if(!data.success) {
                // continue working
            } else {
                // throw an error
            }
        }, 'json');
    }, 3000);
});

But this example produces a timeout for every typed character and I get about 20 AJAX requests if I type-in 20 characters.

On this fiddle I demonstrate the same problem with a simple alert instead of an AJAX.

Is there a solution for this or I'm just using a bad approach for this?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about timeout