防抖与节流方法

<!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>防抖与节流实现方式</title>
    </head>

    <body>
        <input type="text">
        <div style="width: 200px;height: 200px; background: red;" class="box"></div>
    </body>
    <script>
        // 防抖:对频繁触发的事件,只希望最后一次触发、
        let ip = document.querySelector('input');
        // ip.addEventListener('input', demo);未改前
        ip.addEventListener('input', antiShake(demo, 2000));
        // 防抖函数
        function antiShake(fn, time) {
            let timeOut = null;
            return args => {
                if (timeOut) clearTimeout(timeOut);
                timeOut = setTimeout(fn, time)
            }
        }
        function demo() {
            console.log(' 发起请求')
        }
        // 节流:对频繁触发的事件,按照一定的评率触发
        // 应用场景:1.提交表单,2高频事件
        let box = document.querySelector('.box');
        // box.addEventListener('touchmove', demo);未改前
        box.addEventListener('touchmove', throttle(demo, 2000));
        function throttle(fn, time) {
            let timeOut = null;
            return args => {
                if (!timeOut) {
                    timeOut = setTimeout(() => {
                        fn();
                        timeOut = null;
                    }, time);
                }
            }
        }
    </script>

</html>

 

posted @ 2022-09-12 16:39  前端搬运工bug  阅读(24)  评论(0编辑  收藏  举报