防抖和节流

防抖和节流是项目开发中,经常使用到得是两个优化点;

防抖
节流的基本意思是,如果一个函数持续触发,在一定的时间后执行一次,如果这段时间内一直触发,都只会在这个时间后执行一次;适用于那些在连续触发时只关心最后一次触发的场景

项目实际中用到的场景:输入框搜索、监听页面滚动、键盘事件、窗口resize事件

// 防抖  
function debounce(func, delay) {  
  let timeout;  
  return function() {  
    const context = this;  
    const args = arguments;  
    clearTimeout(timeout);  
    timeout = setTimeout(function() {  
      func.apply(context, args);  
    }, delay);  
  };  
} 

节流

防抖的基本意思是,如果一个函数持续触发,在这段时间内只执行一次;适用于那些需要在一定时间内保持执行的场景

项目实际中用到的场景:滚动事件、输入事件、动画效果、定时任务等

// 节流  
function throttle(func, delay) {  
  let timer=null;  
  return function() {  
    const context = this;  
    const args = arguments;  
    if (!timer) {
      timer = setTimeout(function() {  
      	func.apply(context, args);  
        timer= null;  
      }, delay);  
    }  
  };  
}

这里举例一个滚动到底部加载更多数据使用节流的例子

methods: {
  // 获取数据
  getList(){
  },
  throttle(func, delay) {  
	  let timer=null;  
	  return function() {   
	    const args = arguments;  
	    if (!timer) {  
	      timer = setTimeout(function() {  
	      	func.apply(this, args);  
	        timer= null;  
	      }, delay);  
	    }  
	  };  
	},
    handleScroll() {
      const windowScrollTop =
        window.pageYOffset || document.documentElement.scrollTop;
      const windowHeight =
        window.innerHeight || document.documentElement.clientHeight;
      const contentHeight = document.getElementById("content").offsetHeight;
      // 判断是否滚动到底部
      if (windowScrollTop + windowHeight >= contentHeight) {
        if (this.pageNum >= this.totalPages) {// 数据已经获取完毕
          return;
        }
        this.isScroll = true;
        this.pageNum += 1;
        this.getList();
        console.log("滚动到底部了");
      }
    },
  },
mounted() {
    window.addEventListener(
      "scroll",
      this.throttle(this.handleScroll, 500),
      true
    );
  },

  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值