Skip to content

Instantly share code, notes, and snippets.

@TexRx
Forked from kof/defer 1
Created October 23, 2013 04:34
Show Gist options
  • Save TexRx/7112669 to your computer and use it in GitHub Desktop.
Save TexRx/7112669 to your computer and use it in GitHub Desktop.
(function(global){
var $ = global.jQuery || global,
D = Date,
now = D.now || function() {
return (new D).getTime();
};
// if once is true, fn will be executed only once if called more then one times during the time in delay.
// if once is not defined or false, fn will be executed periodically, period is delay.
$.defer = function(fn, delay, once) {
if (!delay || typeof delay === 'boolean') {
once = delay;
delay = 100;
}
var ret,
lasttime, currenttime,
enabled = true,
wrapper, enable;
if (once) {
wrapper = function() {
currenttime = now();
if (!lasttime || currenttime - lasttime > delay) {
ret = fn.apply(this, arguments);
}
lasttime = currenttime;
return ret;
};
} else {
enable = function() {
enabled = true;
};
wrapper = function() {
if (enabled) {
ret = fn.apply(this, arguments);
enabled = false;
setTimeout(enable, delay);
}
return ret;
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( $.guid ) {
wrapper.guid = fn.guid = fn.guid || $.guid++;
}
return wrapper;
};
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment