zoukankan      html  css  js  c++  java
  • 有个叫函数节流的东西

    某些场景下,比如响应鼠标移动或者窗口大小调整的事件,触发频率比较高。若处理函数稍微复杂,需要较多的运算执行时间,响应速度跟不上触发频率,往往会出现延迟,导致假死或者卡顿感。

    为了解决这个问题,我们只能通过减少执行函数的次数来提高响应速度。

    throttle 和 debounce 是解决请求和响应速度不匹配问题的两个方案。二者的差异在于选择不同的策略。

    • throttle 等时间间隔执行函数。
    • debounce 时间间隔 t 内若再次触发事件,则重新计时,直到停止时间大于或等于 t 才执行函数。

    THROTTLE

    function throttle(fn, threshhold, scope) {
      threshhold || (threshhold = 250);
      var last,
          timer;
      return function () {
        var context = scope || this;
    
        var now = +new Date(),
            args = arguments;
        if (last && now - last + threshhold < 0) {
          // hold on to it
          clearTimeout(deferTimer);
          timer = setTimeout(function () {
            last = now;
            fn.apply(context, args);
          }, threshhold);
        } else {
          last = now;
          fn.apply(context, args);
        }
      };
    }

    调用方法

    $('body').on('mousemove', throttle(function (event) {
      console.log('tick');
    }, 1000));
    

      

    DEBOUNCE

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

      调用方法

    $('input.username').keypress(debounce(function (event) {
      // do the Ajax request
    }, 250));
    

      

  • 相关阅读:
    软件开发测试模式:迭代→全功能模式
    LUN挂载到Linux主机后,如何对磁盘进行分区
    MySQL性能优化方法四:SQL优化
    MySQL性能优化方法三:索引优化
    MySQL性能优化方法二:表结构优化
    MySQL性能优化方法一:缓存参数优化
    MySQL配置文件my.ini或my.cnf的位置
    javascript今生前世
    如何在sublime中使用sass
    全栈最后一公里
  • 原文地址:https://www.cnblogs.com/laneyfu/p/6419722.html
Copyright © 2011-2022 走看看