wordpress跳转手机站,seo优化在线诊断,百度网站收录,网站建设开发ppt模板下载1 防抖 高频触发事件时#xff0c;执行损耗高的操作#xff0c;连续触发过程中#xff0c;只执行最后一次。
高频事件#xff1a;input scroll resize等。损耗高#xff1a;网络请求、dom操作。 实现防抖步骤#xff1a;1.在回调函数中判断timer是否存在#xff0c;存在…1 防抖 高频触发事件时执行损耗高的操作连续触发过程中只执行最后一次。
高频事件input scroll resize等。损耗高网络请求、dom操作。 实现防抖步骤1.在回调函数中判断timer是否存在存在就清理计时器重新计时执行。2.在实现debounce函数时注意返回函数和传入的函数参数都不能时回调函数否在造成this丢失。3. debounce函数中返回函数顶层使用this保存回调函数使用apply调用。 4.要使传递参数可行顶层函数解构赋值参数然后再回调apply时传入参数注意不需要解构...args时就是个数组。
// 防抖 防止js函数在短时间内被频繁调用减少性能消耗以及视觉抖动或者网络消耗服务器资源
// 防抖原理再触发频率高的事件中执行耗费性能的操作连续操作后只有最后一次操作生效
// 频率高的事件resize, input, scroll, mousemove, mouseover, mouseout, keyup, keydown, keypress
// 耗费性能的操作dom操作网络请求// 事件触发后延迟一段时间执行函数如果在这段时间内再次触发事件则重新计时
let timer null
document.getElementById(btn).addEventListener(click , (){timer clearTimeout(timer)timer setTimeout((){console.log(click__debounce)}, 500)
})// 也可以使用lodash库中的debounce方法lodash(func, [wait0], [options{}])
class _ {static debounce(callback, wait){let timer null// 返回不能使用箭头函数否则无法获取this中的dom元素return function(...args){// 存储调用时的this一般是dom元素const _this thistimer clearTimeout(timer)timer setTimeout((){// 通过apply将this指向调用时的dom元素callback.apply(_this, args)}, wait)}}
}// 传入函数不能使用箭头函数否则无法绑定this
const debounceFunc _.debounce(function(e){console.log(e)console.log(this)console.log(input)
}, 500)document.querySelector(input).addEventListener(input, debounceFunc)
2 节流 高频触发事件时执行损耗高的操作连续触发过程中在设置好的单位时间内只执行一次。 流程和防抖类似区别在于每次判断定时器是否存在如果存在就不执行任何操作如果定时器不存在那么需要重新设置定时器并且再定时器的回调函数内部执行末尾清除定时器。代码如下所示
// 节流 频繁触发事件时减少触发次数提高性能
// 例如视频播放时 保存播放进度
// 防抖原理再触发频率高的事件中执行耗费性能的操作连续操作后单位事件内只有一次生效
// lodash库中的throttle方法lodash(func, [wait0], [options{}])
let timer_t undefined
document.getElementById(btn_t).addEventListener(click, () {if(!timer_t){timer_t setTimeout((){console.log(click throttle)timer_t undefined}, 1000)}
})_.throttle function(callback, wait){let timer undefinedreturn function(...args){_this thisif(!timer){timer setTimeout((){callback.apply(_this, args)timer undefined}, 1000)}}
}const throttleFunc _.throttle(function(e){console.log(this)console.log(e)console.log(click throttle)
})document.getElementById(input_t).addEventListener(input, throttleFunc)
3 配套文件index.html 新建index.js将上述代码拷贝即可在控制台查看效果index.html内容如下
!DOCTYPE html
html langen
headmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleDocument/title
/head
body
divbutton idbtnclick_debounce/buttonbutton idbtn_tclick_throttle/buttoninput typetext idinputinput typetext idinput_tscript src08_index.js/script
/div
/body
/html