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 需要是数组形式。

  • 相关阅读:
    Ado.Net 实体框架学习笔记3
    Ado.Net 实体框架学习笔记1
    PV3D的小练习~太阳系八大行星
    AS3数组的应用,flash制作流星雨~
    电脑安全措施小贴士(摘)
    Windows下MySql批处理命令
    命令行批量改文件名
    汉字转拼音(asp)(摘录)
    sql server login与user的区别(摘)
    MySql四舍五入
  • 原文地址:https://www.cnblogs.com/Fcode-/p/13358699.html
Copyright © 2011-2022 走看看