欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

函数防抖和函数节流

程序员文章站 2022-07-02 20:23:29
...

在网页开发中,onmousemove,onkeydown,onscroll,onresize 等事件会频繁的触发绑定函数。为了优化性能,我们会用到函数防抖和函数节流。

  • 函数防抖
function debounce(fn){
    var timer = null;
    return function(){
        clearTimeout(timer)
        timer = setTimeout(function(){
            fn();
        },500)
    }
}
function log(){
    console.log(1);
}
document.onmousemove = debounce(log)

函数防抖,当鼠标移动的时候,不会频繁的触发log方法。而是延迟500毫秒之后,再触发log方法。如果这500毫秒中又来了一次鼠标事件,则直接清除前面的延时任务,重新记时。如果鼠标一直不停的移动,则只有最后一次的鼠标事件会触发log方法。

  • 函数节流
function throttle(fn){
    var start = new Date(); 
    var timer = null;
    return function(){
        var now = new Date();
        clearTimeout(timer);
        if(now - start > 2000){
            fn();
            start = now;
        }else{
            timer = setTimeout(function(){
                fn();
            },500);
        }
    }
}
function log(){
    console.log(1);
}
document.onmousemove = throttle(log)

函数节流,和上诉函数防抖的区别在于,当鼠标不停的移动的时候,不会只执行一次log方法。而是每隔2秒就会执行一次log方法。