-
为什么要封装?
1、将函数封装起来增强了程序的安全性
2、减少了重复代码的书写,需要使用时只需要传入参数调用即可,这样使代码更加容易维护 -
什么是防抖?
防抖的原理就是点击一次把上次的写在定时器里面的执行内容连同定时器一起清除,然后在规定时间后执行内容。 -
防抖函数的封装
function debounce(fn,delay){
var timer = null
return function(){
if(timer){
clearTimeout(timer)
}
var arg = arguments[0]
timer = setTimeout(function(){
fn(arg)
},delay)
}
}
function show(ev){
console.log(ev)
}
document.onwheel = debounce(show,1000)
-
什么是节流?
不论点击多少次在规定的时间内只执行那一次 -
节流函数的封装
function throttle(fn,delay){
var timer = null
return function(){
if(timer){
return
}
var arg = arguments[0]
var that = this
timer = setTimeout(function(){
fn.call(that,arg)
timer = null
},delay)
}
}
function show(e){
console.log(e)
}
document.onclick = throttle(show,5000)
- 为什么要设置节流和防抖?
如果一个网页没有设置节流和防抖,那么当遇到用户高频率的点击时很容易造成浏览器的崩溃,所以我们才需要设置节流和防抖来优化性能,提高用户体验