js 防抖和节流的区别和使用 函数去抖(debounce)函数节流(throttle)

目的

以下场景往往由于事件频繁被触发,因而频繁执行DOM操作、资源加载等重行为,导致UI停顿甚至浏览器崩溃。

  • window对象的resizescroll事件
  • 拖拽时的mousemove事件
  • 射击游戏中的mousedownkeydown事件
  • 文字输入、自动完成的keyup事件

实际上对于window的resize事件,实际需求大多为停止改变大小n毫秒后执行后续处理;而其他事件大多的需求是以一定的频率执行后续处理。针对这两种需求就出现了debounce和throttle两种解决办法。

throttle(又称节流)和debounce(又称去抖)其实都是函数调用频率的控制器,

debounce去抖

当调用函数n秒后,才会执行该动作,若在这n秒内又调用该函数则将取消前一次并重新计算执行时间,举个简单的例子,我们要根据用户输入做suggest,每当用户按下键盘的时候都可以取消前一次,并且只关心最后一次输入的时间就行了。

throttle节流

throttle将一个函数的调用频率限制在一定阈值内,例如1s内一个函数不能被调用两次。

以下为实战演示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">点击</button>
</body>
<script>
// 防抖 
function fangdou(fn,d){
    var delay = d || 600
    var timer ;
    return function(){
        var _this =this ;
        var arg =arguments;
        if(timer){
            clearTimeout(timer)
        }
        timer =setTimeout(function(){
            timer =null;
            fn.apply(_this,arg)
        },delay)
    }
}
function jieliu(fn,d){
    var delay = d || 600
    var timer;
    var last;
    return function(){
        var _this =this ;
        var arg =arguments;
        var now = +new Date();
        if(last && now-last <delay){
            clearTimeout(timer);
            timer = setTimeout(function() {
                        last = now;
                        fn.apply(_this, arg);
                    }, delay);
        }else{
            last = now
            fn.apply(_this, arg);
        }
}
}
// 时间戳
    // btn.onclick=function(){
    //     console.log(111)
    // }
    // btn.onclick=fangdou(function(){
    //     console.log(111,this)
    // },500)

       btn.onclick=jieliu(function(){
        console.log(111,this)
    },1000)
</script>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_44360943/article/details/108632298