Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active March 5, 2025 14:13
Show Gist options
  • Save colelawrence/bfc11379c95238f7389b719b15099f23 to your computer and use it in GitHub Desktop.
Save colelawrence/bfc11379c95238f7389b719b15099f23 to your computer and use it in GitHub Desktop.
Loop protection counter in TypeScript
import { DevError, debounce } from "@project/prelude";
export class LoopError extends DevError {
constructor(
message: string,
public readonly debounceMs: number,
public readonly maxCount: number,
) {
super(`${message} (exceeded ${maxCount} calls in ${(debounceMs * 0.001).toFixed(1)}s)`);
}
}
export function createCounterWithLoopProtection({ debounceMs = 1000, maxCount = 20, message = "loop detected" } = {}) {
let count = 0;
let max = maxCount;
const scheduleClearLoopDetection = debounce(debounceMs, () => {
max = count + maxCount;
});
return () => {
count++;
scheduleClearLoopDetection();
if (count > max) {
throw new LoopError(message, debounceMs, maxCount);
}
return count;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment