首页 > 其他 > 详细

防抖动

时间:2016-10-09 14:14:31      阅读:110      评论:0      收藏:0      [点我收藏+]
 1假如有一个 doThings() 的方法来响应 window.onresize 事件,但这个方法执行一次需要消耗一定资源,因此不希望它频繁的执行,于是我们不直接将 doThings() 绑定到 window.onresize ,而是再定义一个 handleResize() 的方法专门处理 window.onresize,在这个方法里至少过 50ms 才调用一次 doTings(),并且每隔 200ms 必执行一次 doTings(),请实现 handleResize() 方法。
 2 
 3 参考答案:
 4 function doThings() {
 5     // a lot of things
 6 }
 7 function handleResize() {
 8     var timer = null,
 9         delay = 50,
10         must_do = 200,
11         last_time;
12     return function() {
13         clearTimeout(timer);
14         var now_time = +new Date;
15         if (!last_time) {
16             last_time = now_time;
17         } else if (now_time - last_time > must_do) {
18             doThings();
19             last_time = now_time;
20         } else {
21             timer = setTimeout(function() {
22                 doThings();
23                 last_time = +new Date;
24             }, delay);
25         }
26     };
27 }
28 window.onresize = handleResize();

 

防抖动

原文:http://www.cnblogs.com/suoking/p/5941435.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!