防抖与节流方法
<!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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现