javascript之函数节流

函数节流原理:

  设置一个定时器setTimeout,让执行的函数延缓一段时间之后再去执行,如果在这段时间内,该函数又触发了,那就清除原来的setTimeout,创建一个新的setTimeout,依此类推下去,就执行了函数节流。

函数封装:

1 function throttle(method, context) {
2     clearTimeout(method.tId);
3     method.tId = setTimeout(function(){
4         method.call(context);
5     }, 100);
6 }

调用:

1 window.onresize = function(){
2     throttle(myFunc);
3 }

另一种封装方法:

 1 var throttle = function(fn, delay){
 2     var timer = null;
 3     return function(){
 4         var context = this, args = arguments;
 5         clearTimeout(timer);
 6         timer = setTimeout(function(){
 7             fn.apply(context, args);
 8         }, delay);
 9     };
10  };

调用:

1 window.onresize = throttle(myFunc, 100);

  第一种方法,把上下文变量当做函数参数,直接可以定制执行函数的this变量;后一个函数优势在于把延迟时间当做变量。

原文地址:https://www.cnblogs.com/wuzhuo/p/3990489.html