提升性能之节流函数和我关于箭头函数this的探索

373 阅读2分钟

个人感悟整理,不喜勿喷,有建议或者错误请大佬们指出。

     优化网络请求性能之
     函数节流 就是预定一个函数只有在大于或者等于执行周期时才执行,周期内调用不执行

     
     例如: 抢购疯狂点击, 节流 是将多次执行变成每隔一点时间执行
      防抖是通过多次执行变为最后一次执行
     
     
     
 

直接上代码:html

<div id="show">0</div>
<button id="btn">click</button>

js

    var odiv = document.getElementById("show");
    var obtn = document.getElementById("btn");
     obtn.onclick = function () {
       odiv.innerText = parseInt(odiv.innerText) + 1;
     };
     
     
     obtn.onclick = thtottle(buy, 1000)

    function buy(e) {
        //-------------------------------业务函数
        odiv.innerText = parseInt(odiv.innerText) + 1;
        console.log(this, e);
    }
    

正常情况下:如上的代码已经完成了 我们点击按钮的需求,但是此时如果疯狂恶意点击,页面就会疯狂执行,如果点击按钮是向后台发起请求呢,会很大的耗费我们服务器的性能,造成恶劣的影响。我们可以采取节流去解决这一情况

```
 节流函数:是将多次执行变成每隔一点时间执行,大于间隔时间才可以执行

function thtottle(handler, wait) {
    var lastTime = 0;
    console.log(this)
      
    return function() {
        var nowTime = new Date().getTime();
        if (nowTime - lastTime > wait) {
            handler.apply(this, arguments);
            // handler();  如果不改变this指向,相当于  buy() buy函数执行,buy函数是写在window中的,所有执行buy函数  ,打印的this 为window,event  为undefined
            console.log(this)
            lastTime = nowTime
        }
    }
}
普通函数的this环境,是谁调用,就指向谁

//绑定点击事件的函数
obtn.onclick = thtottle(buy, 1000);


以上就完成了节流函数的编写和应用。   
以下是个人关于箭头函数的纠结。。 
如果把 节流函数的 return  写成 箭头函数

function throttle(handler, time) {
          let lastTime = 0
            return (e) => {
                let nowTime = new Date().getTime();
                if (nowTime - lastTime > time) {
                     console.log(this);
                     console.log(arguments)
                         // handler 
                     handler.apply(obtn, e);
                     lastTime = nowTime
                 }
            }
      }
     
     /* 
            1: 关于 这里的this 指向:因为箭头函数没有this指向,
                this指向是 他外层,即throttle  函数的this指向 ,而this 声明在了window 中,所以指向window
           2: handler 是指buy  window 可以调用buy,,但是实际上应该是 dom元素调用buy,且buy函数的参数也要传递进来
            3:   所以要改变this指向可以让 this 指向 obtn
            4: 但是这里的参数 指的是当前 this环境下的 arguements,所以arguements--》[function print(){},3000]
            5:写成箭头函数会很麻烦,所以这里还是写成普通函数吧,
            6:或许某天写头函数我能处理好了。。。

            */