美文网首页
throttle与debounce函数

throttle与debounce函数

作者: 勿以浮沙筑高台 | 来源:发表于2017-03-16 00:49 被阅读16次

    throttle()是函数调用的频度控制器,控制连续执行时的时间间隔。

    function throttle (fn, delay) {
      let curr = +new Date(),
          last_exec = 0,//最近一次调用的时间
          diff, //时间差
          context;//上下文
    
      return function () {
        let args = arguments;//保存每次调用的参数
        curr = +new Date();
        context = this;
        diff = curr - last_exec -delay;
        if (diff >= 0) {
          last_exec = curr;
          fn.apply(context, args);
        } else {
          last_exec = curr - diff;
          setTimeout(() => {
              fn.apply(context, args);
          }, -diff)
        }
    
      }
    }
    

    主要应用场景:

    1. 鼠标移动,mousemove 事件
    2. DOM 元素动态定位,window 对象的 resizescroll 事件

    debounce() 是空闲时间必须大于或等于 一定值的时候,才会执行调用方法,控制空闲时间的间隔。比如我们做autocomplete,这时需要我们很好的控制输入文字时调用方法时间间隔。一般是第一个输入的字符马上开始调用,根据一定的时间间隔重复调用执行的方法。

    function debounce(fn, delay) {
      let timer = null;
      return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay)
      }
    }
    

    debounce主要应用的场景比如:
    文本输入keydown 事件,keyup 事件,例如做autocomplete

    相关文章

      网友评论

          本文标题:throttle与debounce函数

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