防抖和节流

1.防抖:就是为函数添加一个定时器,延时多久以后触发,如果在这个时间内再次触发了这个函数,会把上一个定时器清除掉,并从新计时。使用场景:实时搜索,按钮防止重复点击;

使用定时器和闭包来实现。

  //使用方法,一定要有变量接收或者是setTimeout(debounce,100)这样的类型
  this
.c=this.debounce(this.a,4000);
   debounce
= (func, wait = 5000) => { console.log(1) let timer return function(...args) { if (timer) clearTimeout(timer) timer = setTimeout(() => { func.apply(this, args) }, wait) } } a = () =>{ console.log('sb') } handleInput = (e) => { this.c()

    // const c =
this.debounce(this.a,4000);
    // c();
   // 这样是不可以的,每次函数触发都会重置timer,导致闭包失效,每次timer都是undefined
}
原文地址:https://www.cnblogs.com/dongkx/p/10179109.html