您的位置:首页 > 其它

函数节流及防抖

2019-04-09 20:30 169 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_39434651/article/details/89161038

鼠标移动事件onmousemove, 滚动滚动条事件onscroll等瞬间的操作都会导致这些事件会被高频触发。 如果事件的回调函数较为复杂,可能会导致响应跟不上触发,出现页面卡顿,假死现象
防抖: 当持续触发事件时,每一次都要清空定时器,重新开始。
eg:实时搜索
实现1:

var timer = null;
function debounce (){
clearTimeout(timer);
timer = setTimeout(function(){
console.log("函数防抖");
}, 300);
};

实现2:

function debunce(handler,delay){
var timer = null;
return function(){
var _self = this,args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
handler.apply(_self,args);
},delay);
}

节流:当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
eg:窗口调整(调整大小),页面滚动(滚动),抢购时疯狂点击(鼠标按下)
实现1:

var timer = null;
function throttle(){
if(!timer){
timer = setTimeout(function(){
console.log("函数节流");
timer = null;
}, 300);
}
};

实现2:

function throttle(handler, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
handler.apply(context, args);
timer = null;
}, delay);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: