节流函数 (学者说)

节流函数

定义 规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。

实现原理 原理是用时间戳来判断是否已到回调该执行时间,记录上次执行的时间戳,然后每次触发 scroll 事件执行回调,回调中判断当前时间戳距离上次执行时间戳的间隔是否已经到达 规定时间段,如果是,则执行,并更新上次执行的时间戳。

应用场景

  • 拖拽:固定时间内只执行一次,防止超高频次触发位置变
  • 缩放:监控浏览器resize。
  • 动画:避免短时间内多次触发动画引起性能问题。

vue中代码使用演示

  • 外部定义节流函数
export function throttle(fn,delay){
    
    
 var lastTime;
 var timer;
 var delay = delay || 200;
 return function() {
    
    
   var args = arguments;
   // 记录当前函数触发的时间
   var nowTime = Date.now();
   if (lastTime && nowTime - lastTime < delay) {
    
    
     clearTimeout(timer);
     timer = setTimeout(function () {
    
    
       // 记录上一次函数触发的时间
       lastTime = nowTime;
       // 修正this指向问题
       fn.apply(this, args);
     }, delay);
   }else{
    
    
     lastTime = nowTime;
     fn.apply(this, args);
   }
 }
} 
  • 组件中的使用
//导入节流函数
import {
    
    throttle} from '文件路径'

//方法中的使用
事件方法名:throttle(function(){
    
    
    	//要执行的方法,例:拖拽
    	this.getList()
},300)

getList(){
    
    
 this.$refs.a.onmousedown = function (e) {
    
    
    //设置定位使元素脱离文档流
      this.$refs.a.style.position = 'absolute';
      var disx = e.pageX - el.offsetLeft;
      var disy = e.pageY - el.offsetTop;
      document.onmousemove = function (e) {
    
    
        this.$refs.a.style.left = e.pageX - disx + 'px';
        this.$refs.a.style.top = e.pageY - disy + 'px';
      }
      document.onmouseup = function () {
    
    
        document.onmousemove = document.onmouseup = null;
      }
    }
}

猜你喜欢

转载自blog.csdn.net/SSansui/article/details/112777529
今日推荐