Skip to content

Instantly share code, notes, and snippets.

@zbinlin
Last active January 19, 2016 08:04
Show Gist options
  • Save zbinlin/f09ad2e41f2eea2d72c4 to your computer and use it in GitHub Desktop.
Save zbinlin/f09ad2e41f2eea2d72c4 to your computer and use it in GitHub Desktop.
Debounce
/*
* @param {Function} func
* 需要进行去抖的函数
* @param {number} wait
* 去抖的时间间隔
* @param {boolean} [lead = false]
* 是否要在开始执行
* @returns {Function}
* 返回一个去抖函数
*/
function debounce(func, wait, lead) {
var tid, timestamp,
that, args;
function delayed(timeout) {
tid && clearTimeout(tid);
tid = setTimeout(function () {
handler();
}, timeout);
}
function now() {
return Date.now ? Date.now() : new Date().getTime();
}
function handler() {
return func.apply(that, args);
}
return function __debounced__() {
args = arguments;
that = this;
if (lead) {
if (!timestamp || (now() - timestamp) >= wait) {
handler();
}
timestamp = now();
} else {
delayed(wait);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment