在网站的交互过程中,有很多操作会被频繁的触发,这样就给浏览器和服务器带来了不小的负担。节流和防抖就是很好的降低频率的方式
节流
将一个函数的执行控制在一定的时间间隔外就是节流,下例将log函数控制再1秒钟内只能触发一次
let lastTime = 0
function log(){
let nowTime = new Date()
if(nowTime - lastTime > 1000){
console.log(11)
lastTime = nowTime
}
}
for(let i = 0 ;i < 100;i++){
log()
}
封装一下就能更好的用于多个函数
function throttle(fn, wait){
let lastTime = 0
return function (){
let nowTime = new Date()
if(nowTime - lastTime > wait){
lastTime = nowTime
fn.apply(this, arguments)
}
}
}
function log(){
console.log(11)
}
document.onclick = throttle(log, 1000)
防抖
在停止连续操作一定时间后,才执行最近一次的操作。
let timer = null
function log(){
clearTimeout(timer)
timer = setTimeout(() => {
console.log('~~pq~~')
}, 1000)
}
封装以后的就能用于多个函数
<input type="text" id="text" onkeydown="newLog(this.value)">
function debounce(fn, delay){
let timer = null
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
let newLog = debounce((str) => {
console.log(str)
}, 1000)