Files
taimed/common/debounce.js
2025-08-13 14:53:35 +08:00

60 lines
1.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
let timeout = null
/**
* 防抖原理一定时间内只有最后一次操作再过wait毫秒后才执行函数
*
* @param {Function} func 要执行的回调函数
* @param {Number} wait 延时的时间
* @param {Boolean} immediate 是否立即执行
* @return null
*/
function debounce(func, wait = 500, immediate = false) {
// 清除定时器
if (timeout !== null) clearTimeout(timeout)
// 立即执行,此类情况一般用不到
if (immediate) {
const callNow = !timeout
timeout = setTimeout(() => {
timeout = null
}, wait)
if (callNow) typeof func === 'function' && func()
} else {
// 设置定时器当最后一次操作后timeout不会再被清除所以在延时wait毫秒后执行func回调方法
timeout = setTimeout(() => {
typeof func === 'function' && func()
}, wait)
}
}
function throttle(fn, delay = 1000, immediate = false) {
console.log("进入节流对象")
let timer
let status = false // 是否为重复点击状态
return function () {
let _this = this
let args = arguments
if (immediate) {
console.log("立即执行参数 执行一次方法")
fn.apply(_this, args)
immediate = false
return
}
if (status) {
console.log("当前点击状态为正在重复点击,请稍等片刻后在点击执行")
return
}
console.log("执行节流:当前执行了一次点击方法")
fn.apply(_this, args)
status = true // 修改状态
timer = setTimeout(() => {
console.log("规定时间到,重置状态,可以重新调用")
status = false
}, delay)
}
}
export {
debounce,
throttle
}