函数防抖
定义: 多次触发事件后, 事件处理函数只执行一次, 并且是在触发操作结束时执行.
原理: 对处理函数进行延时操作, 若设定的延时到来之前, 再次触发事件, 则清除上一次的延时操作定时器, 重新定时.
- let timer;
- Windows.onscroll = function () {
- if(timer){
- clearTimeout(timer)
- }
- timer = setTimeout(function () {
- // 滚动条位置
- let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
- console.log('滚动条位置:' + scrollTop);
- timer = undefined;
- },200)
- }
函数防抖的适用性:
通过上面的例子, 我们知道我们可以通过函数防抖, 解决了多次触发事件时的性能问题.
比如, 我们在监听滚动条位置, 控制是否显示返回顶部按钮时, 就可以将防抖函数应用其中.
- let startTime = Date.now(); // 开始时间
- let time = 500; // 间隔时间
- let timer;
- Windows.onscroll = function throttle(){
- let currentTime = Date.now();
- if(currentTime - startTime>= time){
- let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
- console.log('滚动条位置:' + scrollTop);
- startTime = currentTime;
- }else{
- clearTimeout(timer);
- timer = setTimeout(function () {
- throttle()
- }, 50);
- }
- }
来源: http://www.qdfuns.com/article/39828/8932e66f2a3a9a5b253fc74ac3feb40b.html