对于高频发生的事件,我们给事件的回调函数设置间隔时间。在间隔时间内如果事件再次被触发,则重新计时;在间隔时间内事件如果未被触发,则执行事件的回调函数。

    普通版:

    1. function debounce(fn, interval) {
    2. //fn为要执行的函数
    3. //interval为等待的时间
    4. var timeout; //定时器
    5. return function() { //返回一个闭包
    6. var context = this, args = arguments; //先把变量缓存
    7. clearTimeout(timeout); //核心实现:不管什么情况,先清除定时器
    8. timeout = setTimeout(function() {
    9. timeout = null;
    10. fn.apply(context, args);
    11. }, interval); //延迟执行
    12. };
    13. };
    14. //使用
    15. var myEfficientFn = debounce(function() {
    16. //你要做的事
    17. }, 250);
    18. window.addEventListener('resize', myEfficientFn);

    立即执行版:

    1. function debounce(fn, interval, immediate) {
    2. //fn为要执行的函数
    3. //interval为等待的时间
    4. //immediate判断是否立即执行
    5. var timeout; //定时器
    6. return function() { //返回一个闭包
    7. var context = this, args = arguments; //先把变量缓存
    8. var later = function() { //把稍后要执行的代码封装起来
    9. timeout = null; //成功调用后清除定时器
    10. if(!immediate) fn.apply(context, args); //不立即执行时才可以调用
    11. };
    12. var callNow = immediate && !timeout; //判断是否立即调用,并且如果定时器存在,则不立即调用
    13. clearTimeout(timeout); //不管什么情况,先清除定时器,这是最稳妥的
    14. timeout = setTimeout(later, interval); //延迟执行
    15. if(callNow) fn.apply(context, args); //如果是第一次触发,并且immediate为true,则立即执行
    16. };
    17. };
    18. //使用
    19. var myEfficientFn = debounce(function() {
    20. //你要做的事
    21. }, 250, true);
    22. window.addEventListener('resize', myEfficientFn);