JS之防抖(debounce)和节流(throttle)以及其使用场景

编程入门 行业动态 更新时间:2024-10-26 12:25:06

JS之<a href=https://www.elefans.com/category/jswz/34/1752808.html style=防抖(debounce)和节流(throttle)以及其使用场景"/>

JS之防抖(debounce)和节流(throttle)以及其使用场景

防抖(debounce)
当事件高频率触发时(keyup事件,scroll事件,浏览器大小),为了不加重浏览器的负担,而仅仅在其结束后的一段时间再进行相应的操作

  // 最实在的写法let timer = nullipt.addEventListener('keyup',function(event) {// 如果有清空if (timer) {clearTimeout(timer)}timer = setTimeout(function() {console.log(ipt.value)timer = null},1500)})

上面的这种写法显然不合理,如果有多个元素想要实现防抖操作就不可以了,封装一下

function debounce(fn,detail) {let timer = nullreturn function() {if(timer == null) {clearTimeout(timer)}timer = setTimeout(fn,detail)}
}
function testfn() {console.log("操作函数")
}
bnt.addEventListener('keyup',debounce(testfn,1000))

防抖(debounce)应用场景
场景一: 搜索场景,输入搜索关键字以后,会在停留几秒后,做出搜索答案
场景二: 浏览器滚动条滚动到一定的程度的时候,会有一个向上的箭头出现

节流(throttle)

当特定事件被持续触发的时候,为了避免浏览器资源被过度占用,保证在一定的时间内仅被调用一次。

function throttle(fn,detail = 200) {let timer = nullreturn function() {if (timer) { return }timer = setTimeout(() => {fn.apply(this,arguments)timer = null},detail)}}ipt123.addEventListener("drag",throttle(function(event) {console.log(event)console.log(event.offsetX,event.offsetY)},1000))ipt123.addEventListener("drag",throttle(function(event) {console.log(event)console.log(event.offsetX,event.offsetY)},1000))

节流场景
drag被不断的调用,保证在一段时间内仅被调用一次

更多推荐

JS之防抖(debounce)和节流(throttle)以及其使用场景

本文发布于:2023-07-28 16:31:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:防抖   场景   JS   throttle   debounce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!