js 防抖函数和节流函数

目录

防抖动函数

代码 

使用

节流函数 

代码 

使用


防抖动函数

在delay时间内,若多次触发该函数,则会重新计时

 适用场景

1.监听图片的加载是否完成,用图片的load事件,会被频繁的触发,可使用

2.键盘的keyup事件,当用户停止输入时,才发送请求,可使用

代码 

// 防抖动函数,不让事件频繁的进行触发函数
export function debance(func, delay) {
  //创建一个初始值
  let timer = null;
  return function(...args) {
    //判断是否存在,若存在,则清楚
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

使用

 //设置防抖动函数
 this.refresh = debance(this.$refs.detailScroll.refresh, 100)

 //使用防抖动函数
 this.$bus.$on('detailGoodsItemImgLoad', () => {
    this.refresh();
 })

节流函数 

在delay单位时间内,只能触发一次函数。如果在这个时间内触发多次函数,只有一次生效。

适用场景

1.若需要每隔一段时间就进行一次网络请求,可以使用

2.轮播图的频繁触发滑动,设定某个时间只能滑动一次,可以使用

代码 

//函数节流
function throttle(fn,delay) {
    // 定义一个锁
    let lock= true; 
    return function (...args) {
        // 若被锁住,则直接返回
        if (!lock) return;
        //若没被锁,进来后,立即把锁设置为false
        lock= false;
        setTimeout(() => { 
            fn.apply(this, args);
            //时间一过,开锁
            lock= true;
        }, delay);
    };
}

使用

 function demo(){
   console.log('----')
 }
 //设置节流函数
 this.refresh = throttle(demo, 100)

 //使用节流函数
 this.$bus.$on('detailGoodsItemImgLoad', () => {
    this.refresh();
 })

 

你可能感兴趣的:(js)