函数节流
在指定时间内只触发一次,防止频繁触发
如scroll事件
//参数
//fn 事件触发执行的函数
//delay 距离下一次触发时间
//调用throttle函数,当thrttle执行后active会保存在内存中
//同时会返回一个函数出来
throttle(fn, delay) {
let active = true;
return function(...params) {
if (!active) {
return
}
active = false;
setTimeout(function() {
fn.apply(this, params);
active = true;
}, delay);
}
}
函数节流调用
let box = document.querySelector('.box');
box.onclick = throttle(() => {
console.log('我点击了box')
}, 200)
教学版本
function fn( func,delay,mustExec ){
var timer = null;
var start = new Date();
return function(){
clearTimeout( timer );
if( new Date()-start > mustExec ){
func();
start = new Date();
}else{
timer = setTimeout(function(){
func();
},delay)
}
}
}