防抖与节流

防抖函数

let timer
clearTimeout(timer)
timer = setTimeout(function(){

},delay)

实际的应用

使用echarts时,改变浏览器宽度的时候,希望重新渲染
echarts的图像,可以使用此函数,提升性能。(虽然echarts里有自带的resize函数)
典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时,解决搜索的bug

// 防抖的函数
function debounce(callback,delay){
  let timer
  return function(arg){
    clearTimeout(timer)
    timer = setTimeout(() => {
      callback(arg)
    }, delay);
  }
}
function func(value){
  console.log(value)
}
var input = document.getElementById('input');
var debounceFn = debounce(func,2000)
input.addEventListener('keyup',function(e){
  debounceFn(e.target.value)
})

节流函数

当持续触发事件的时候,保证一段时间内,只调用一次事件处理函数
一段时间内,只做一件事情

实际应用 表单的提交

典型的案例:鼠标不断点击触发,规定在n秒内多次点击只有一次生效

function throttle(func,wait){
  let timeOut
  return function(){
    if(!timeOut){
      timeOut = setTimeout(() => {
        func()
        timeOut = null;
      }, wait);
    }
  }
}
function handle(){
  console.log(Math.random())
}
document.getElementById('button').onclick = throttle(handle,2000)

防抖节流在图片懒加载中的运用

let num = document.getElementsByTagName('img').length;
let img = document.getElementsByTagName('img');
let n = 0; // 存储图片加载到的位置,避免每次都从第一张图片开始遍历
let isLoading = false;  // 是否当前容器/页面的图片加载完成
let _clientHeight = document.documentElement.clientHeight;  // 可见区域高度
let _scrollTop = document.documentElement.scrollTop || document.body.scrollTop;  //滚动条距离顶部高度

// 监听窗口变化重新计算可视区域
function computedClientHeight(){
  _clientHeight = document.documentElement.clientHeight; // 可见区域高度
}
// 页面载入完毕加载可视区域内的图片
lazyLoad();
function lazyLoad(){
  // 获取滚动条距离顶部高度
  isLoading = n >= num;
  _scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  for(let i = n;i<num;i++){
    if(img[i].offsetTop<_clientHeight+_scrollTop){
      if(img[i].getAttribute('src')==''){
        img[i].src = img[i].getAttribute('data-src')
      }
      n = i + 1
    }
  }
}

function throttle(func,wait,flag){
  let timeOut;
  return function(){
    if(flag) return;
    if(!timeOut){
      timeOut = setTimeout(() => {
        timeOut = null;
        func()
      }, wait);
    }
  }
}

function debounce(callback,delay){
let timer;
return function(arg){
  clearTimeout(timer);
  timer = setTimeout(() => {
    callback(arg)
  }, delay);
}
}

// 使用了节流函数~实现性能较好的懒加载
window.addEventListener('scroll',throttle(lazyLoad,100,isLoading))
// 使用了防抖函数~优化不断触发的窗口变化
window.addEventListener('resize',debounce(computedClientHeight,800))
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值