在网页中,可能会有部分用户会频繁触发事件,而频繁的请求服务器的操作可能会使导致卡顿,甚至浏览器的崩溃。防抖和节流就是为了解决这一类的问题
节流:
理解:防止用户频繁的访问服务器,设置一个功能函数,先实现一次操作,然后通过计算点击频率来过滤掉多余的操作
实现:用Date对象计算上次操作距离本次操作的间隔,如果超过设置时间,则不实现操作
代码:
function show() { 这里是点击事件的的主要函数
console.log('hello')
console.log(this)
}
function throttle(handler,wait){ //handler是要进行节流的函数,wait是
等待时间
var lastTime = 0;
return function(){
var nowTime = new Date().getTime(); //获取当前时间
if(nowTime - lastTime> wait){
handler.apply(this,arguments);//作用域问题apply方法
继承this和参数
lastTime = nowTime; //更新最后时间
}
}
}
var Debounce=throttle(show,2000)
document.querySelector('button').addEventListener('click',Debounce)