防抖与节流原理与区别

一:函数的节流: 一定时间内只触发一次 

可以是直接给一个定时器,按时触发,

// 函数节流 var canRun = true; document.getElementById("throttle").

onscroll = function(){

if(!canRun){ // 判断是否已空闲,如果在执行中,则直接return return;

}

canRun = false;

setTimeout(function(){

console.log("函数节流"); canRun = true; 
}, 300); };

也可以根据一个条件判断触发
节流demon   http://demo.deanhan.cn/suggestion.html
  二:函数防抖 在规定的时间内只触发一次,如果多次触发,清除上次触发的事件,重新计算时间, 
// 防抖就是事件 :多次触发事件后,
//事件处理函数只执行一次,
//并且是在触发操作结束时执行
//事件多次触发清除之前的定时器
let timer;
window.onscroll = function() {
console.log(12)
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
//滚动条位置
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
timer = undefined;
}, 200)
}

 


 

posted on 2018-12-10 17:59  田庚的博客园  阅读(1895)  评论(0编辑  收藏  举报

导航