函数节流

此文章只为了帮助自己记忆 。

以下场景往往由于事件频繁被触发,因而频繁执行DOM操作、资源加载等重行为,导致UI停顿甚至浏览器崩溃。

  1. window对象的resize、scroll事件

  2. 拖拽时的mousemove事件

  3. 射击游戏中的mousedown、keydown事件

  4. 文字输入、自动完成的keyup事件

实际上对于window的resize事件,实际需求大多为停止改变大小n毫秒后执行后续处理;而其他事件大多的需求是以一定的频率执行后续处理。针对这两种需求就出现了throttle。

 方法1:全部东西合并成一个。

var debounce = function(idle, action){
  var last
  return function(){
    var ctx = this, args = arguments
    clearTimeout(last)
    last = setTimeout(function(){
        action.apply(ctx, args)
    }, idle)
  }
}

方法2:方法1的加强版,让时间累积到一个值,马上触发。

        function throttle(fn,delay,mustDoTime){
            var last;
            var id;
            return function(){
                var current = +new Date();
                var args = arguments;
                var $this = this;
                clearTimeout(id);
                //第一次时间是一样的
                if(!last){
                    last = current;
                }
                //时间超过了必须执行的时间,就直接执行
                if(current - last >= mustDoTime){
                    fn.apply($this,args);
                    last = current;
                }else{
                    id = setTimeout(function(){
                        fn.apply($this,args);
                    },delay);
                }
            }
        }
        var obj = {name:"大叔"};
        var test = throttle(function(){
            console.log(this.name);
        },100,100);
        for(var index = 0;index < 10000;index ++){
            test.call(obj);
        }
原文地址:https://www.cnblogs.com/geilishu/p/5232591.html