Skip to content

Instantly share code, notes, and snippets.

@6174
Created August 21, 2013 09:01
Show Gist options
  • Save 6174/6292036 to your computer and use it in GitHub Desktop.
Save 6174/6292036 to your computer and use it in GitHub Desktop.
throttle 函数啦 *_*
/**
* 版本1
* Throttles a call to a method based on the time between calls.
* @param {Function} fn The function call to throttle.
* @param {Object} [context] context fn to run
* @param {Number} [ms] The number of milliseconds to throttle the method call.
* Passing a -1 will disable the throttle. Defaults to 150.
* @return {Function} Returns a wrapped function that calls fn throttled.
* @member KISSY
*/
function throttle(fn, ms, context) {
ms = ms || 150;
if (ms === -1) {
return (function () {
fn.apply(context || this, arguments);
});
}
var last = +new Date();
return (function () {
var now = +new Date();
if (now - last > ms) {
last = now;
fn.apply(context || this, arguments);
}
});
}
var now = require('../time/now');
/**
*/
function throttle(fn, delay){
var context, timeout, result, args,
cur, diff, prev = 0;
function delayed(){
prev = now();
timeout = null;
result = fn.apply(context, args);
}
function throttled(){
context = this;
args = arguments;
cur = now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (! timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
return throttled;
}
module.exports = throttle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment