页面渲染优化——防抖与节流

引用:http://www.cnblogs.com/coco1s/p/5499469.html

防抖

简单来说,就是在resize或者scroll等操作特别频繁的时候,规定触发事件的频率,不要太频繁

  • 设定计时器,setTimeout(func, wait)
  • 如果在执行func之前,wait时间内就又有了新动作,则clearTimeout(timeout)清空计时器
  • 直到wait时间内没有新动作了,才执行func
// 简单的防抖动函数
function debounce(func, wait, immediate) {
    // 定时器变量
    var timeout;
    return function() {
        // 每次触发 scroll handler 时先清除定时器
        clearTimeout(timeout);
        // 指定 xx ms 后触发真正想进行的操作 handler
        timeout = setTimeout(func, wait);
    };
};
 
// 实际想绑定在 scroll 事件上的 handler
function realFunc(){
    console.log("Success");
}
 
// 采用了防抖动
window.addEventListener('scroll',debounce(realFunc,500));
// 没采用防抖动
window.addEventListener('scroll',realFunc);

节流

防抖方式只有当动作停下才会执行函数,但是如果遇到图片滑动时懒加载、Ajax请求之类,我们想要在滑动同时进行加载时,可以规定一个最小加载时间。就是虽然没有停下,但是一旦到了这个时间,就会进行一次加载。

// 简单的节流函数
function throttle(func, wait, mustRun) {
    var timeout,
        startTime = new Date();
 
    return function() {
        var context = this,
            args = arguments,
            curTime = new Date();
 
        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔,触发 handler
        if(curTime - startTime >= mustRun){
            func.apply(context,args);
            startTime = curTime;
        // 没达到触发间隔,重新设定定时器
        }else{
            timeout = setTimeout(func, wait);
        }
    };
};
// 实际想绑定在 scroll 事件上的 handler
function realFunc(){
    console.log("Success");
}
// 采用了节流函数
window.addEventListener('scroll',throttle(realFunc,500,1000));
 

猜你喜欢

转载自www.cnblogs.com/xiaoyuchen/p/10538435.html