欢迎光临散文网 会员登陆 & 注册

节流与防抖

2022-10-18 09:40 作者:对白浅浅  | 我要投稿

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <style>

        html,body{

            height: 500%;

        }

    </style>

</head>

<body>

    <button id="button">

        按钮

    </button>

    <!-- 节流与防抖 -->

    <script>

        // 节流:一个函数执行一次后,只有大于设定的执行周期才会执行第二次

        function throttle(fn,delay){

            let lastTime = 0

            return function(){

                let nowTime = Date.now()

                if(nowTime - lastTime > delay){

                    fn.call(this)  //修正this指向问题

                    lastTime = nowTime

                }

            }

        }

        document.onscroll=throttle(function(){

            console.log("scroll 时间被触发了"+ Date.now())

        },2000)

       


        //防抖:一个需要频繁触发的函数,在规定时间内只让最后一次生效,前面的不生效

        function debounce(fn,delay){

            let timer =null

            return function(){

                clearTimeout(timer)

                timer = setTimeout(function(){

                    fn.apply(this)

                },delay)

            }

        }


        document.getElementById("button").onclick = debounce(function(){

            console.log("点击事件被触发了"+Date.now())

        },500)


        // 节流进阶

        function debounce2(fn,delay,immediate){  //immediate为是否先执行一次节流

            let timer=null

            return function(){

                clearTimeout(timer)

                if(immediate){

                    let doOnce = !timer

                    timer = setTimeout(function(){

                        timer=null

                    },delay)

                    if(doOnce){

                        fn.apply(this)

                    }

                }else{

                    // 如果没有设置第三个参数,就是什么时候停止操作,之后delay时间才执行

                    timer = setTimeout(function(){

                        fn.apply(this)

                    },delay)

                }

            }

        }

    </script>

   

</body>

</html>


节流与防抖的评论 (共 条)

分享到微博请遵守国家法律