Skip to content

Instantly share code, notes, and snippets.

@zbinlin
Created December 13, 2014 12:50
Show Gist options
  • Save zbinlin/24fe18233741de7481d3 to your computer and use it in GitHub Desktop.
Save zbinlin/24fe18233741de7481d3 to your computer and use it in GitHub Desktop.
Throttle
/*
* @param {Function} func
* 需要进行节流的函数
* @param {number} wait
* 节流的时间间隔
* @param {boolean} [trail]
* 是否要在结尾执行
* @returns {Function}
* 返回一个节流函数
*/
function throttle(func, wait, trail) {
if ("function" !== typeof func) {
throw new TypeError;
}
wait = +wait || 0;
trail = !!trail;
var tid, timestamp,
that, args;
function delayed(timeout) {
tid = setTimeout(function () {
handler();
timestamp = now();
}, timeout);
}
function now() {
return Date.now ? Date.now() : new Date().getTime();
}
function handler() {
return func.apply(that, args);
}
return function _() {
args = arguments;
that = this;
var remaining = 0;
trail && tid && clearTimeout(tid);
if (!timestamp || (remaining = now() - timestamp) >= wait) {
timestamp = now();
handler();
} else if (trail) {
delayed(wait - remaining);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment