首頁  >  文章  >  web前端  >  javascript函數節流與防手震的應用場景介紹

javascript函數節流與防手震的應用場景介紹

不言
不言轉載
2018-10-19 15:06:332585瀏覽

這篇文章帶給大家的內容是關於php變數作用域的用法介紹(程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

throttle 節流

事件觸發到結束後只執行一次。

應用場景

觸發mousemove事件的時候, 如滑鼠移動。

觸發keyup事件的情況, 如搜尋。

觸發scroll事件的時候, 譬如滑鼠向下捲動停止時觸發載入資料。

coding

方法1  防手震

// function resizehandler(fn, delay){
//   clearTimeout(fn.timer);
//   fn.timer = setTimeout(() => {
//      fn();
//   }, delay);
// }
// window.onresize = () => resizehandler(fn, 1000);

方法2 閉包 防手震

function resizehandler(fn, delay){
    let timer = null;
    return function() {
      const context = this;
      const args=arguments;
      clearTimeout(timer);
      timer = setTimeout(() => {
         fn.apply(context,args);
      }, delay);
    }
 }
 window.onresize = resizehandler(fn, 1000);

#debounce 防手震

事件出發後一定的事件內執行一次。

應用場景

window 變更觸發resize事件是, 只執行一次。

電話號碼輸入的驗證, 只需停止輸入後進行一次。

coding

function resizehandler(fn, delay, duration) {
        let timer = null;
        let beginTime = +new Date();
        return function() {
          const context = this;
          const args = arguments;
          const currentTime = +new Date();
          timer && clearTimeout(timer);
          if ((currentTime - beginTime) >= duration) {
            fn.call(context, args);
            beginTime = currentTime;
           } else {
             timer = setTimeout(() => {
               fn.call(context, args)
             }, delay);
           }
        }
      }

        window.onresize = resizehandler(fn, 1000, 1000);

以上是javascript函數節流與防手震的應用場景介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除