函数防抖.html 1.46 KB
<!DOCTYPE>
<HTML>

<head>
    <title>函数节流</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <style>
     *{
         margin: 0;
         padding: 0;
     }
    </style>
</head>

<body>
    <div style="background: pink;height: 100vh;">函数节流:指定时间间隔内只会执行一次任务</div>
    <div style="background: orange;height: 100vh;" id="text"></div>
    <script>
       //方法一:Date
        function throttle_01(fn,timeout = 300){    
            let old = new Date().getTime();
            return function(){
                let now = new Date().getTime(); 
                if(now - old < timeout){
                  return
                }    
                old = now;                  
                fn()
            }
        }
         //方法二:定时器:set
         function throttle(fn,timeout = 300){
            let canRun = true
            let fn1 = fn();
            return function(){
                if(!canRun){
                    return
                }
                setTimeout(() => {
                  fn1();
                  canRun = true
                }, timeout);
                canRun = false;
            }
        }
        let count = 0;
        function handle (){
            document.getElementById('text').innerHTML = count++
        }
        window.addEventListener('scroll',throttle(handle))
    </script>
</body>

</HTML>