| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import { ref, onUnmounted } from 'vue'
- import { onHide } from "@dcloudio/uni-app";
- /**
- * 防抖 Hook
- * @param {Function} fn - 需要防抖的函数
- * @param {number} [delay=300] - 防抖延迟时间(毫秒)
- * @param {boolean} [immediate=false] - 是否立即执行
- * @returns {Ref<Function>} 防抖后的函数
- */
- export function useDebounce(fn, delay = 300, immediate = false) {
- const debounceRef = ref()
- let timer = null
- debounceRef.value = (...args) => {
- if (timer) {
- // 清除现有的定时器
- clearTimeout(timer)
- }
- if (immediate && !timer) {
- // 如果设置了立即执行且没有定时器,则立即调用函数
- fn(...args)
- } else {
- // 设置定时器,在延迟时间后执行函数
- timer = setTimeout(() => {
- fn(...args)
- timer = null
- }, delay)
- }
- }
- // 页面隐藏时清理定时器
- onHide(() => {
- if (timer) {
- clearTimeout(timer)
- }
- })
- return debounceRef
- }
- /**
- * 节流 Hook
- * @param {Function} fn - 需要节流的函数
- * @param {number} [delay=300] - 节流间隔时间(毫秒)
- * @param {boolean} [immediate=false] - 是否立即执行
- * @returns {Ref<Function>} 节流后的函数
- */
- export function useThrottle(fn, delay = 300, immediate = false) {
- const throttleRef = ref()
- let lastTime = 0
- let timer = null
- throttleRef.value = (...args) => {
- const now = Date.now()
- if (immediate && !lastTime) {
- // 如果设置了立即执行且是第一次调用,则立即执行
- fn(...args)
- lastTime = now
- return
- }
- if (now - lastTime >= delay) {
- // 如果距离上次执行已超过间隔时间,直接执行
- fn(...args)
- lastTime = now
- } else if (!timer) {
- // 如果在间隔时间内,使用定时器确保在间隔结束后执行
- timer = setTimeout(() => {
- fn(...args)
- lastTime = Date.now()
- timer = null
- }, delay)
- }
- }
- // 页面隐藏时清理定时器
- onHide(() => {
- if (timer) {
- clearTimeout(timer)
- }
- })
- return throttleRef
- }
|