index.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // @ts-nocheck
  2. /**
  3. * 节流函数,用于限制函数的调用频率
  4. * @param fn 要进行节流的函数
  5. * @param interval 两次调用之间的最小间隔时间
  6. * @returns 节流后的函数
  7. */
  8. export type ThrottleOptions = {
  9. /**
  10. * 是否在节流开始时立即执行
  11. * @default true
  12. */
  13. leading ?: boolean;
  14. /**
  15. * 是否在节流结束后执行最后一次调用
  16. * @default true
  17. */
  18. trailing ?: boolean;
  19. }
  20. /**
  21. * 节流函数,限制函数在一定时间内只能执行一次
  22. * @param func 需要节流的函数
  23. * @param wait 节流间隔时间(毫秒)
  24. * @param options 配置选项
  25. * @param options.leading 是否在节流开始时立即执行(默认 true)
  26. * @param options.trailing 是否在节流结束时执行最后一次调用(默认 true)
  27. * @returns 返回节流后的函数
  28. */
  29. // #ifndef APP-ANDROID
  30. export function throttle<T extends (...args : any[]) => any>(
  31. func : T,
  32. wait : number,
  33. options : ThrottleOptions = {}
  34. ) : (...args : Parameters<T>) => void {
  35. let lastCallTime = 0;
  36. let timerId : ReturnType<typeof setTimeout> | null = null;
  37. const { leading = true, trailing = true } = options;
  38. return function (...args : Parameters<T>) {
  39. const now = Date.now();
  40. const timeSinceLastCall = now - lastCallTime;
  41. // 1. 如果 leading=true 且距离上次调用超过 wait,立即执行
  42. if (leading && timeSinceLastCall >= wait) {
  43. lastCallTime = now;
  44. func.apply(this, args);
  45. }
  46. // 2. 如果 trailing=true,设置定时器在 wait 时间后执行最后一次调用
  47. else if (trailing && !timerId) {
  48. timerId = setTimeout(() => {
  49. lastCallTime = Date.now();
  50. func.apply(this, args);
  51. timerId = null;
  52. }, wait - timeSinceLastCall);
  53. }
  54. };
  55. }
  56. // #endif
  57. // #ifdef APP-ANDROID
  58. export function throttle<T extends any|null>(
  59. func: (args : T) => void,
  60. wait : number,
  61. options : ThrottleOptions = {}
  62. ) : (args : T) => void {
  63. let lastCallTime = 0;
  64. let timerId = -1;
  65. const { leading = true, trailing = true } = options;
  66. return function (args : T) {
  67. const now = Date.now();
  68. const timeSinceLastCall = now - lastCallTime;
  69. // 1. 如果 leading=true 且距离上次调用超过 wait,立即执行
  70. if (leading && timeSinceLastCall >= wait) {
  71. lastCallTime = now;
  72. func(args);
  73. }
  74. // 2. 如果 trailing=true,设置定时器在 wait 时间后执行最后一次调用
  75. else if (trailing && timerId > -1) {
  76. timerId = setTimeout(() => {
  77. lastCallTime = Date.now();
  78. func(args);
  79. timerId = -1;
  80. }, wait - timeSinceLastCall);
  81. }
  82. };
  83. }
  84. // #endif