函数防抖
一个函数在被触发的 n 秒后再执行(延迟执行), 如果 n 秒内再次被触发,计时器则重新开始计时。
/**
* debounce
* @param {Function} fn 需要进行防抖的函数
* @param {Number} delay 延迟的时间 ms
* @param {Boolean} triggerNow 首次是否立即触发
*/
function debounce (fn, delay, triggerNow) {
var t = null;
return function () {
var _this = this,
args = arguments;
if (t) {
clearTimeout(t);
}
if (triggerNow) {
var exec = !t;
t = setTimeout(function () {
t = null;
}, delay);
if (exec) {
fn.apply(_this, args);
}
} else {
t = setTimeout(function () {
fn.apply(_this, args);
}, delay)
}
}
}
节流函数
一个函数在被触发后的 n 秒内如果再次触发,不执行。
/**
* throttle
* @param {Function} fn 需要进行节流的函数
* @param {Number} delay 延迟的时间 ms
*/
function throttle (fn, delay) {
var t = null,
begin = new Date().getTime();
return function () {
var _this = this,
args = arguments,
cur = new Date().getTime();
if (t) {
clearTimeout(t);
}
if (cur - begin < delay) {
t = setTimeout(function () {
fn.apply(_this, args);
}, delay)
} else {
fn.apply(_this, args);
begin = cur;
}
}
}