防抖
當(dāng)連續(xù)不斷的觸發(fā)事件函數(shù)時(shí),先直接觸發(fā)一次或不觸發(fā),在觸發(fā)停止的一段時(shí)間后執(zhí)行一次
利用閉包
非立即執(zhí)行
function debounce(func, await) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, arguments);
}, await);
};
}
立即執(zhí)行
function debounce(func, await) {
let timer;
return function () {
計(jì)時(shí)器一旦開(kāi)啟timer便始終為一個(gè)正整數(shù)
if (timer) {
clearTimeout(timer);
}
let doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, await);
if (doNow) {
func.apply(this, arguments);
}
};
}
結(jié)合版
function debounce(func, await, immediate) {
let timer;
return function () {
if (timer) {
clearTimeout(timer);
}
if (immediate) {
let doNow = !timer;
timer = setTimeout(() => {
timer = null;
}, await);
if (doNow) {
func.apply(this, arguments);
}
} else {
timer = setTimeout(() => {
func.apply(this, arguments);
}, await);
}
};
}
節(jié)流
當(dāng)持續(xù)不停的觸發(fā)事件函數(shù)時(shí)绞愚,每過(guò)一段時(shí)間便會(huì)觸發(fā)一次
利用閉包
時(shí)間戳版
function debounce(func, interval) {
注意給prev一個(gè)初始值
let prev = 0;
return function () {
now = Date.now();
if (now - prev >= interval) {
func.apply(this, arguments);
prev = now;
}
};
}
計(jì)時(shí)器版
function debounce(func, interval) {
let timer;
return function () {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null;
}, interval);
}
};
}
結(jié)合版
function debounce(func, interval, type) {
if (type === 1) {
let prev = 0;
return function () {
let now = Date.now();
if (now - prev >= interval) {
prev = now;
func.apply(this, arguments);
}
};
}
if (type === 2) {
let timer;
return function () {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments);
timer = null;
}, interval);
}
};
}
}
使用
dom.onmousemove = debounce(func, 1000);
this
指向dom
元素本身郎任,arguments[0]
指向事件參數(shù)e