zoukankan      html  css  js  c++  java
  • JS实现函数节流方法

    函数节流可以一定程度得减少系统的损耗,方法如下:

    /**
     * 函数节流方法
     * @param {Function} fn 需要进行节流执行的函数
     * @param {Number} delay 延时执行的时间
     * @param {Number} atleast 至少多长时间触发一次
     * @return {Function} 返回节流执行的函数
     */
    function throttle (fn, delay, atleast = 0) {
      let timer = null; //定时器
      let previous = 0; //记录上一次执行的时间
      
      return (...args) => {
        let now = +new Date();   //当前时间戳
        if (!previous) previous = now; // 赋值开始时间
        
        if (atleast && (now - previous) > atleast) {
          fn.apply(this, args);  //文章下面有给出该行代码的理解
          // 重置上一次开始时间为本次结束时间
          previous = now;
          timer && clearTimeout(timer);
        } else {
          timer && clearTimeout(timer); // 清除上次定时器
          timer = setTimeout(() => {
            fn.apply(this, args);
            console.log('else')
            previous = 0;
          }, delay);
        }
      }
    }

    其中 fn.apply(this,  args) 不难理解,我们通过一段代码来看:

      function person(name) {
        this.name = name;
        this.sayname = function() {
          alert(this.name)
        }
      }
      
      function student(name) {
        person.apply(this, arguments)
      }
    
      var studenta = new student('xiaoming')
      studenta.sayname();
    此时,屏幕会出现 alert('xiaoming')的效果。

    由此可见 fn.apply(this,  args) 实现了对 fn 的继承, args 需要是数组形式。

  • 相关阅读:
    C#中方法的分类、定义、调用(3)
    C#中的输入和输出与类和对象(2)
    .net中的数据类型与数据转换(1)
    android第二章控件2
    android第二章控件1
    安卓 第一章
    二进制文件的读写与小结
    字符流
    File类与字节流
    字节流
  • 原文地址:https://www.cnblogs.com/Fcode-/p/13358699.html
Copyright © 2011-2022 走看看