防抖(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)以及其使用场景
发布评论