js实现页面防抖动

问题:针对频繁触发scoll resize绑定的事件函数,有可能短时间多次触发时事件,影响性能

思路:多个函数调用合成一次,给定时间后仅调用最后一次

// 包装事件的debounce函数

function debounce(func, delay){

    let timer = null;    

    return function(){

         let context = this; // 通过 ‘this’ 和 ‘arguments’ 获取函数的作用域和变量

        let args = arguments; 

        clearTimeout(timer);

        timer = setTimeout(function(){

                func().apply(context, args);

扫描二维码关注公众号,回复: 3196968 查看本文章

        }, delay)

    }

}

// 当用户滚动时被调用的函数

function foo(){

    cosnole.log("todo somethind");

 }

// 元素绑定scoll事件,触发包装函数debounce

let elem = document.getElementById('container');

elem.addEventListener('scroll', debounce(foo, 2000));

猜你喜欢

转载自blog.csdn.net/rongmingye/article/details/82458342