delayedChange plugin

attach handler to text input. control delayed execution

by artoodetoo

HTML

<div id="get">
    <input id="number" type="text" value="123">
    <br>
    <input id="string" type="text" value="abc">
</div>
<div id="set">#1: 123-abc</div>

JavaScript

(function ($) {
    $.fn.delayedChange = function (handler, delay) {
        var $this = $(this);
        var oldVal = $this.val();
        if (typeof delay == 'undefined') delay = 1000;

        $this.on('input keyup', function () {
            clearTimeout($this.data('timer'));
            $this.data('timer', setTimeout(function () {
                $this.removeData('timer');
                var newVal = $this.val();
                if (newVal != oldVal) {
                    if (handler($this, newVal)) oldVal = newVal;
                }
            }, delay));
        });
    };
})(jQuery);

var counter = 1;

function myfunc(item, value) {
    var text = '#' + (++counter) + ': ' + $('#number').val() + ':' + $('#string').val();
    $('#set').text(text);
    return true;
}

$(function () {
    $('#number').delayedChange(myfunc);
    $('#string').delayedChange(myfunc);
});