JSFiddle - React, Tailwind, and code Playground
by JAAulde
HTML
<p>Two second delay:</p>
<p><input type="text" id="someInput1" value="" /></p>
<p>Three second delay:</p>
<p><input type="text" id="someInput2" class="delayedKeyup3000" value="" /></p>
<p><input type="text" id="someInput3" class="delayedKeyup3000" value="" /></p>
JavaScript
//Write the plugin
( function( global )
{
var setTimeout = global.setTimeout,
clearTimeout = global.clearTimeout,
$ = global.jQuery,
defaultOpts = {
delay: 1000,
execute: function(){}
};
$.fn.delayedKeyup = function( opts )
{
opts = $.extend( {},defaultOpts, opts );
return this
.bind( 'keyup', function()
{
var ele = this,
$this = $( ele ),
args = arguments;
window.clearTimeout( $this.data( 'timerId' ) );
$this.data(
'timerId',
window.setTimeout(
function()
{
opts.execute.apply( ele, args );
},
opts.delay
)
);
} );
};
}( window ) );
//Use the plugin
$( '#someInput1' ).delayedKeyup( {
delay: 2000,
execute: function( e )
{
alert( this.id + ' received input #' + e.which );
}
} );
//Use the plugin some more
$( '.delayedKeyup3000' ).delayedKeyup( {
delay: 3000,
execute: function( e )
{
alert( this.id + ' received input #' + e.which + '\nValue is: ' + this.value );
}
} );