tijiao
This commit is contained in:
59
src/common/js/debounce.js
Normal file
59
src/common/js/debounce.js
Normal file
@@ -0,0 +1,59 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user