-
-
Save TexRx/7112669 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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