节流
控制执行的次数
简单理解就是在一定的时间内同一个事件只能触发一次,只有超过这个时间才能再次触发。
-
监听鼠标滚动事件(不加节流)
<style> body { height: 2000vh; } </style> <body> <script> window.onscroll = function () { console.log(1); } </script> </body>
效果演示:
-
监听鼠标滚动事件(简单加节流)
<style> body { height: 2000vh; } </style> <body> <script> let flag = true; window.onscroll = function () { if (flag) { setTimeout(() => { console.log('hahaha'); flag = true; }, 500) }; flag = false; } </script> </body>
- 多了一个全局变量;
- 如果要添加业务逻辑就会有点乱。
封装节流函数
function throttle(fn, delay) {
let flag = true;
return function () {
if (flag) {
setTimeout(() => {
fn.call(this); // 重定向this的指向
flag = true;
}, delay)
};
flag = false;
}
}
window.onscroll = throttle(function () {
console.log('hahhaha'); // 请注意这里的this需要重定向
}, 500)
效果展示: