shangfutong-ui/jeepay-ui-uapp-agent/util/debounce.js

46 lines
1.0 KiB
JavaScript
Raw 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.

/**
* @param {Function} fn 需要执行的方法因this指向问题建议不使用箭头函数
* @param {Number} delay 间隔时间默认值100
* @param {Boolean} promptly 是否立即执行默认false
* **/
export const debounce = (fn, delay = 100, promptly) => {
let timer = null
return function (...args) {
// 立即执行
if (promptly) {
// 当timer为null时执行
if (!timer) fn.apply(this, args)
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
timer = null
}, delay)
} else {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
}
/**
* @param {Function} fn 需要执行的方法因this指向问题建议不使用箭头函数
* @param {Number} delay 间隔时间默认值100
* **/
const throttle = (fn, delay = 100) => {
let valid = true
return function (...args) {
if (!valid) {
return
}
valid = false
fn.apply(this, args)
setTimeout(() => {
valid = true
}, delay)
}
}