节流: 多次执行一段逻辑的时候,每隔一段时间,执行一次 例如技能冷却
防抖:让多次执行 只取最后一次 实现逻辑 在执行的过程中不停的重新设定定时器
简单实现代码:
节流
let timer;
onscroll = function () {
//每隔一秒钟执行一次
//判断有没有这个定时器
// console.log(timer);//undefined
if (!timer) {
timer = setTimeout(function () {
console.log(11111);
timer = null;//等于一个布尔值就行
}, 1000)
}
// console.log(timer);
}
防抖
let timer;
onscroll =function(){
console.log(111);
if(timer){
//清除timer
clearTimeout(timer)
}
//定时器
timer = setTimeout(function(){
console.log("最后一次的结果是:" + 111);
},1000)
}