/*
防抖:是指在事件被触发后,在n秒内函数只执行一次,如果在n秒内重复被触发,则重新开始计时
*/
/**
* 防抖函数,计时结束时触发
* @param { Function } callBack
* @param { Number } 延迟秒数
* @returns { Function }
*/
function debounce1 (funs, delay) {
let timer
return function () {
let arg = arguments
if(timer) { clearTimeout(timer) }
timer = setTimeout(() => {
funs(...arg)
}, delay)
}
}
/**
* 防抖函数,立即执行防抖函数:先执行在计时
*/
function debounce2 (funs, delay) {
let timer
return function () {
// 接收参数
let arg = arguments
// 如果timer为true,说明计时还没结束,则取消上次计时,重新开始计时
if (timer) { clearTimeout(timer)}
// 通过timer的值来确定是否执行回调函数
let callNow = !timer
// 利用定时器计时,delay秒内无操作则令timer为null,下次操作立即执行回调
timer = setTimeout(() => {
timer = null
}, delay)
if (callNow) {
funs(...arg)
}
}
}
/*
节流:是指连续触发事件但是在n秒内只执行一次
*/
/**
* 节流函数
*/
function throttle (funs, wait) {
let timer
return function () {
let arg = arguments
if (timer) return
timer = setTimeout(() => {
timer = null
funs(...arg)
}, wait);
}
}
手写防抖和节流函数
最新推荐文章于 2024-05-27 20:46:11 发布