手写防抖&节流
参考
来源:https://www.bilibili.com/video/BV1sN411974w?p=2
细讲:https://zhuanlan.zhihu.com/p/110733457
1. 防抖
// keyup:释放任意按键。
inputEle.addEventListener("keyup", (function(e){ //这是一个自运行函数
var t = null;
return function(){ //真正的事件函数在这里
clearTimeout(t); //每次触发,都把前面的定时器关闭,尽管第一次定时器并不存在
t = setTimeout(function(){ //开启新的定时器
//ajax(...); 发送请求到服务器
}, 300);
}
})())
2. 节流
function throttle (fun,wait) {
let timer = null;
return function () {
// 事件触发,如果之前没有等待的事件,则不作处理
if (!timer) {
timer = setTimeout(function () {
fun();
timer = null;
}, wait);
}
}
}
本文来自博客园,作者:沧浪浊兮,转载请注明原文链接:https://www.cnblogs.com/shixiu/p/15993132.html

浙公网安备 33010602011771号