美文网首页
scroll事件的性能

scroll事件的性能

作者: 请叫我小飞鹅 | 来源:发表于2018-01-11 00:31 被阅读0次
防抖函数:强制一个函数在某个连续时间段内只执行一次
let debounce = (fn, wait) => {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            fn.apply(context, args)
        }, wait);
    };
};
截流函数:固定函数执行的速率
// throttle - 节流:在滚动时防止不停执行逻辑函数,定义当滚动时保证每隔多长时间必须执行一次,其他的一次为防抖
// fn: 逻辑函数
// wait: 当滚动后执行时的时间间隔

let throttle = (fn, wait) => {
    let context, args;
    let last = 0;
    return function () {
        let now = +new Date();
        context = this;
        args = arguments;
        if (now - last > wait) {
            fn.apply(context, args);
            last = now;
        }
    };
};
原生节流:同throttle,只是间隔时间是浏览器的渲染间隔时间,比如chrome每秒渲染60帧,相应的间隔时间为1000/60

// 浏览器动画函数
  const nextFrame =  window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (fn) { window.setTimeout(fn , 1000 / 60); };

   
    // func: 逻辑函数
   let rAF =  function(func){
      return function() {
        let ticking = false; // rAF 触发锁
        if (!ticking) {
          nextFrame(func);
          ticking = true;
        }
      };
    }

应用场景:
scroll ,input,timeUpdate等一些频繁触发的事件。

相关文章

网友评论

      本文标题:scroll事件的性能

      本文链接:https://www.haomeiwen.com/subject/ndnuuxtx.html