防抖和节流代码详解
原创小于 1 分钟防抖节流
防抖和节流代码详解
/**
*
* @param {*} func 需要执行的方法
* @param {*} wait 延迟执行的时间
* @param {*} immediate 是否立即执行
* @description 防抖函数
* @returns
*/
function debounce(func, wait, immediate) {
let timeout;
return function () {
let context = this
let args = arguments
if (timeout) {
clearTimeout(timeout)
}
if (immediate) {
let callNow = !timeout
timeout = setTimeout(function () {
timeout = null
}, wait)
if (callNow) {
func.apply(context, args)
}
} else {
timeout = setTimeout(function () {
func.apply(context, args);
}, wait)
}
}
}
function test() {
console.log('5000ms后执行')
}
const res = debounce(test, 5000, true)
res()
/**
*
* @param {*} func 节流函数
* @param {*} wait 节流时间
* @returns
*/
function throttle(func, wait) {
let preTime = 0
return function () {
let nowTime = Number(new Date());
let context = this
let args = arguments
if (nowTime - preTime > wait) {
func.apply(context, args)
preTime = nowTime
}
}
}
function test() {
console.log('即使调用的再快,1000ms只调用一次throttle')
}
const res = throttle(test, 1000)
setInterval(() => {
res()
}, 50)