//介绍:
//为防止频繁触发事件;例如:onmousemove事件,移动触发,若使用防抖,若一直移动不会执行该事件,停止该事件操作之后,会在延时时间后去只执行,具体尝试便知。
//防抖 应用场景
//1,scroll滚动事件触发
//2,搜索框输入查询
//3,表单验证(ajax)
//4,按钮提交事件(ajax)
//5,resize,浏览器窗口缩放(ajax)
;function debounce(func,wait,immediate){
let timer,result;
let decounced = function(){
//事件对象
let args = arguments;
//改变this指向
let self = this;
clearTimeout(timer);
if(immediate){
//立即执行
let callnow = !timer;
timer = setTimeout(()=>{
timer = null;
},wait);
if(callnow) result = func.apply(self,args);
}else{
//非立即执行
timer = setTimeout(function(){
func.apply(self,args);
},wait)
}
return result
}
//取消防抖执行
decounced.cancel = function(){
clearTimeout(timer);
timer = null;
}
return decounced;
}
//使用介绍
let container = document.querySelector('#warp');
let btn = document.querySelector('#btn');
let dosome = debounce(dosomething,3000,false);
var count = 0;
function dosomething(e){
console.log(e);
console.log(this);
container.innerHTML = count++;
}
container.onmousemove = dosome;
//取消未结束的防抖函数
btn.onclick = function(){
dosome.cancel();
}
//工具库:
//https://underscorejs.net/#each
//https://www.underscore-js.com/functionsrelated