函數(shù)防抖:n秒內(nèi)只要觸發(fā)事件帝际,就重新計(jì)時(shí),事件處理函數(shù)的程序?qū)⒂肋h(yuǎn)不會(huì)被執(zhí)行
/**
* 函數(shù)防抖
* @param {[fn]} 回調(diào)方法
* @param {[time]} 延遲時(shí)間
* @param {[immediate]} 是否立即執(zhí)行
*/
function debounce(fn, time, immediate) {
var timer = null,
result;
var debounced = function() {
var context = this,
args = arguments;
if(timer) clearTimeout(timer);
if(immediate) {
// 如果已執(zhí)行饶辙,不再執(zhí)行
var callNow = !timer;
timer = setTimeout(function() {
timer = null;
}, time);
if(callNow) {
result = fn.apply(context, args);
}
} else {
timer = setTimeout(function() {
result = fn.apply(context, args);
}, time)
}
return result;
}
debounced.cancel = function() {
clearTimeout(timer);
timer = null;
}
return debounced;
}
函數(shù)節(jié)流:事件被觸發(fā)蹲诀,n秒內(nèi)只執(zhí)行一次事件處理函數(shù)
/**
* 函數(shù)節(jié)流
* @param {[fn]} 回調(diào)方法
* @param {[delay]} 延遲時(shí)間
*/
function throttle(fn, delay) {
var timer = null,
begin = new Date().getTime();
return funcion() {
var context = this,
args = arguments,
now = new Date().getTime();
clearTimeout(timer);
if(now - begin >= delay) {
fn.apply(context, args);
begin = now;
} else {
timer = setTimeout(function() {
fn.apply(context, args);
}, delay)
}
}
}