masto
Version:
Mastodon API client for JavaScript, TypeScript, Node.js, browsers
38 lines (37 loc) • 1 kB
JavaScript
import { CustomError } from "ts-custom-error";
import { sleep } from "./sleep.js";
export class ExponentialBackoffError extends CustomError {
constructor(attempts, options) {
super(`Maximum number of attempts reached: ${attempts}`, options);
}
}
// https://en.wikipedia.org/wiki/Exponential_backoff
export class ExponentialBackoff {
props;
attempts = 0;
constructor(props = {}) {
this.props = props;
}
async sleep() {
if (this.attempts >= this.maxAttempts) {
throw new ExponentialBackoffError(this.attempts);
}
await sleep(this.timeout);
this.attempts++;
}
clear() {
this.attempts = 0;
}
get factor() {
return this.props.factor ?? 1000;
}
get base() {
return this.props.base ?? 2;
}
get maxAttempts() {
return this.props.maxAttempts ?? Number.POSITIVE_INFINITY;
}
get timeout() {
return this.factor * this.base ** this.attempts;
}
}