前端学习(1830):前端面试题之节流

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    html,body{
        height: 500%;
    }
    </style>
</head>
<body>
    <script>
        function throwttle(fn,dalay){
            //记录上一次触发的时间
            var lastTime=0;
            return function(){
                //记录当前函数触发的时间
            var nowTime=Date.now();
            if(nowTime-lastTime>dalay){
                fn();
                lastTime=nowTime;
            }
            }
            
        }
        document.onscroll=throwttle(function(){console.log('scroll事件被触发了'+Date.now())},200)
    </script>
</body>
</html>

运行结果

猜你喜欢

转载自blog.csdn.net/weixin_43392489/article/details/107501681