防抖
事件影响函数在一段事件后在执行
应用场景
- 搜索框输入
- scroll 事件滚动触发
- 表单验证
- 按钮提交
- 浏览器缩放事件,resize事件。
const btn = document.querySelector("#btn");
function debounce(func, time, immediate) {
let timeout,
result = null;
let debounced = function () {
let _this = this;
let ars = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
timeout = setTimeout(() => {
result = func.apply(_this, ars);
timeout = null;
}, time);
} else {
timeout = setTimeout(function () {
func.apply(_this, ars);
}, time);
}
return result;
};
debounced.cancel = function () {
clearTimeout(timeout);
timeout = null;
};
return debounced;
}
let count = 0;
let doSome = debounce(fn, 3000);
btn1.onclick = () => {
doSome.cancel();
};
function fn(e) {
console.log(e);
console.log(this);
btn.textContent = count++;
}
btn.onmousemove = doSome;