zoukankan      html  css  js  c++  java
  • 防抖动

     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();
    坚持下去就能成功
  • 相关阅读:
    写在noi之前
    雅礼集训 Day8
    雅礼集训 Day6
    雅礼集训 Day5
    2017雅礼集训 Day4
    2017雅礼集训 Day2
    2017雅礼集训 Day1
    洛谷 P3426 [POI2005]SZA-Template
    Codeforces Round #368 DIV2 C.
    Educational Codeforces Round 16 D&E.
  • 原文地址:https://www.cnblogs.com/suoking/p/5941435.html
Copyright © 2011-2022 走看看