防抖与节流方法

<!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 @   前端搬运工bug  阅读(26)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
    · 使用C#创建一个MCP客户端
    · ollama系列1:轻松3步本地部署deepseek,普通电脑可用
    · 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
    · 按钮权限的设计及实现
    点击右上角即可分享
    微信分享提示