码迷,mamicode.com
首页 > 编程语言 > 详细

javascript之函数节流

时间:2014-09-24 15:24:26      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   java   ar   div   sp   art   

函数节流原理:

  设置一个定时器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变量;后一个函数优势在于把延迟时间当做变量。

javascript之函数节流

标签:style   blog   color   io   java   ar   div   sp   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!