MCPcopy Create free account
hub / github.com/getsentry/sentry-javascript / throttle

Function throttle

packages/replay-internal/src/util/throttle.ts:13–55  ·  view source on GitHub ↗
(
  fn: T,
  maxCount: number,
  durationSeconds: number,
)

Source from the content-addressed store, hash-verified

11 */
12// eslint-disable-next-line @typescript-eslint/no-explicit-any
13export function throttle<T extends (...rest: any[]) => any>(
14 fn: T,
15 maxCount: number,
16 durationSeconds: number,
17): (...rest: Parameters<T>) => ReturnType<T> | typeof THROTTLED | typeof SKIPPED {
18 const counter = new Map<number, number>();
19
20 const _cleanup = (now: number): void => {
21 const threshold = now - durationSeconds;
22 counter.forEach((_value, key) => {
23 if (key < threshold) {
24 counter.delete(key);
25 }
26 });
27 };
28
29 const _getTotalCount = (): number => {
30 return [...counter.values()].reduce((a, b) => a + b, 0);
31 };
32
33 let isThrottled = false;
34
35 return (...rest: Parameters<T>): ReturnType<T> | typeof THROTTLED | typeof SKIPPED => {
36 // Date in second-precision, which we use as basis for the throttling
37 const now = Math.floor(Date.now() / 1000);
38
39 // First, make sure to delete any old entries
40 _cleanup(now);
41
42 // If already over limit, do nothing
43 if (_getTotalCount() >= maxCount) {
44 const wasThrottled = isThrottled;
45 isThrottled = true;
46 return wasThrottled ? SKIPPED : THROTTLED;
47 }
48
49 isThrottled = false;
50 const count = counter.get(now) || 0;
51 counter.set(now, count + 1);
52
53 return fn(...rest);
54 };
55}

Callers 2

throttle.test.tsFile · 0.90
constructorMethod · 0.90

Calls 6

_cleanupFunction · 0.85
_getTotalCountFunction · 0.85
nowMethod · 0.65
getMethod · 0.65
setMethod · 0.65
fnFunction · 0.50

Tested by

no test coverage detected