useDebounceThrottle.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { ref, onUnmounted } from 'vue'
  2. import { onHide } from "@dcloudio/uni-app";
  3. /**
  4. * 防抖 Hook
  5. * @param {Function} fn - 需要防抖的函数
  6. * @param {number} [delay=300] - 防抖延迟时间(毫秒)
  7. * @param {boolean} [immediate=false] - 是否立即执行
  8. * @returns {Ref<Function>} 防抖后的函数
  9. */
  10. export function useDebounce(fn, delay = 300, immediate = false) {
  11. const debounceRef = ref()
  12. let timer = null
  13. debounceRef.value = (...args) => {
  14. if (timer) {
  15. // 清除现有的定时器
  16. clearTimeout(timer)
  17. }
  18. if (immediate && !timer) {
  19. // 如果设置了立即执行且没有定时器,则立即调用函数
  20. fn(...args)
  21. } else {
  22. // 设置定时器,在延迟时间后执行函数
  23. timer = setTimeout(() => {
  24. fn(...args)
  25. timer = null
  26. }, delay)
  27. }
  28. }
  29. // 页面隐藏时清理定时器
  30. onHide(() => {
  31. if (timer) {
  32. clearTimeout(timer)
  33. }
  34. })
  35. return debounceRef
  36. }
  37. /**
  38. * 节流 Hook
  39. * @param {Function} fn - 需要节流的函数
  40. * @param {number} [delay=300] - 节流间隔时间(毫秒)
  41. * @param {boolean} [immediate=false] - 是否立即执行
  42. * @returns {Ref<Function>} 节流后的函数
  43. */
  44. export function useThrottle(fn, delay = 300, immediate = false) {
  45. const throttleRef = ref()
  46. let lastTime = 0
  47. let timer = null
  48. throttleRef.value = (...args) => {
  49. const now = Date.now()
  50. if (immediate && !lastTime) {
  51. // 如果设置了立即执行且是第一次调用,则立即执行
  52. fn(...args)
  53. lastTime = now
  54. return
  55. }
  56. if (now - lastTime >= delay) {
  57. // 如果距离上次执行已超过间隔时间,直接执行
  58. fn(...args)
  59. lastTime = now
  60. } else if (!timer) {
  61. // 如果在间隔时间内,使用定时器确保在间隔结束后执行
  62. timer = setTimeout(() => {
  63. fn(...args)
  64. lastTime = Date.now()
  65. timer = null
  66. }, delay)
  67. }
  68. }
  69. // 页面隐藏时清理定时器
  70. onHide(() => {
  71. if (timer) {
  72. clearTimeout(timer)
  73. }
  74. })
  75. return throttleRef
  76. }