js节流与防抖的代码实现与应用场景简述

it2023-08-11  75

节流

一定时间内只执行一次相关代码 适用场景: 图片懒加载 监听滚动条 如鼠标移动事件中onmousemove、滚动条事件等 ,如若事件触发执行的相关代码中有关于DOM节点的相关操作 又或者 ajax 请求接口,会造成计算机的性能的浪费,这种现象是我们不希望见到的 特点:监听timer这个变量,如果timer为null的时候 才会执行callback

function throttle(callback, wait) { var timer = null return function () { if (!timer) { timer = setTimeout(function () { foo() timer = null }, wait) } } } function foo() { console.log(Math.ceil(Math.random() * 10)) } window.addEventListener("mousemove", throttle(foo, 2000))

防抖

在一系列频繁的操作下 只取最后一次(个人理解) 应用场景: 验证码六位数 在输入最后一位后 自动提交表单 在调整屏幕大小时 有些浏览器 或者页面可能会等到调整完成 才会执行callback 避免多次无意义的排版渲染

function throttle(callback, wait) { var timer = null return function () { if (timer) { clearInterval(timer) } timer = setTimeout(function () { foo() timer = null }, wait) } } function foo() { console.log(Math.ceil(Math.random() * 10)) } window.addEventListener("mousemove", throttle(foo, 2000))

总结: 防抖节流的核心都是setTimeout ,都是为了降低callback的执行频率 节省计算机资源 优化性能 提高用户体验

最新回复(0)