当一些事件触发的时候,有的时候并不想频繁的执行函数;如resize、scroll、mousemove等事件触发的时候
一、防抖
防抖指的是触发事件n秒后才执行函数,如果n秒内再次触发则重新计时
非立即执行
function debounce(func, wait) {
let timeout
return function() {
const context = this
const args = [...arguments]
if (timeout) clearTimeout(timeout)
timeout = setTimeout(() => {
func.call(context, args )
})
}
}
立即执行
function debounce(func, wait) {
let timeout
return function() {
const context = this
const args = [...arguments]
if(timeout) clearTimeout(timeout)
const callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (callNow ) func.call(context, args) }
}
二、节流
节流指的是连续触发事件的时候,只在指定时间内触发一次
function throttle(func, wait) {
let preTime = 0
return function() {
const nowTime = new Date().getTime()
const context = this
const args = [...arguments]
if (nowTime - preTime > wait) {
func.call(context, args)
preTime = nowTime
}
}
}