防抖和節流

1.防抖:就是爲函數添加一個定時器,延時多久之後觸發,若是在這個時間內再次觸發了這個函數,會把上一個定時器清除掉,並重新計時。使用場景:實時搜索,按鈕防止重複點擊;閉包

使用定時器和閉包來實現。app

  //使用方法,必定要有變量接收或者是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
}
相關文章
相關標籤/搜索