您的位置:首页 > 其它

说下防抖和节流

2019-07-12 11:17 148 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_42442445/article/details/95599829

1. 防抖

触发高频率事件在n秒后函数会触发一次,n秒内触发高频率事件,重新计算时间

举个例子:
就像进电梯,电梯开启后,有一群人要进电梯,假如电梯3s内不进人就会关闭,现在不断有人进入。进电梯就是高频率事件,前一个人进去后,后面的人重新开始计时,,事件不断触发。当最后一个人进入后,3s后电梯开始关闭。

var inp = document.getElementById('input');
function debounce(handler,wait) {
var timer = null;
return function () { //返回的匿名函数就是oninput的逻辑处理
clearTimeout(timer);
timer = setTimeout(() => {
handler.apply(this, arguments); //this指向input框,arguments就是input事件e,当做参数传入handler
},wait)
}
}
function sayHi(e) {
console.log(e, this.value);
}
inp.addEventListener('input',debounce(sayHi, 2000))

2. 节流

以时间为单位稀释执行次数,上次执行n秒后可再次执行

var btn = document.getElementById('btn');
function throttle(handler,wait) {
let lastTime = 0;
return function () {
const nowTime = +new Date(); //时间戳
if (nowTime - lastTime > wait) {
handler.apply(this, arguments);
lastTime = nowTime;
}
}
}
function sayHi(e) {
console.log(this,e);
}
btn.onclick = throttle(sayHi, 2000);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: