防抖动

Posted 专注前端开发

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了防抖动相关的知识,希望对你有一定的参考价值。

 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();

 

以上是关于防抖动的主要内容,如果未能解决你的问题,请参考以下文章

js:防抖动与节流

javascript 防抖动

css 防抖动

防抖动

javascript touchstart事件防抖动#js #event

javascript touchstart事件防抖动#js #event