Skip to content

Instantly share code, notes, and snippets.

@joshthewhite
Created December 5, 2011 19:23
Show Gist options
  • Save joshthewhite/1434878 to your computer and use it in GitHub Desktop.
Save joshthewhite/1434878 to your computer and use it in GitHub Desktop.
Timed Bind Plugin for JQuery
/**
* Attaches a handler to an event the fires after a given time interval.
*
* Usage:
* $('input[type="text"]').timedBind('keyup', function (e) {
* var $el = $(e.target);
* alert($el.val());
* });
*/
(function($) {
$.timedBind = { timers: [] };
$.fn.timedBind = function (eventType, callback, options) {
var options = $.extend({
timeout : 750
}, options);
return this.each(function () {
var $el = $(this);
var timer_id = $el.data('timerid');
if (!timer_id) {
var el_id = $el.attr('id');
if (!el_id) {
el_id = new Date.getTime();
}
$el.data('timerid', el_id);
timer_id = el_id;
}
$el.bind(eventType, function (e) {
if ($.timedBind.timers[timer_id]) {
clearTimeout($.timedBind.timers[timer_id]);
}
$.timedBind.timers[timer_id] = setTimeout(function () {
callback(e);
}, options.timeout);
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment