2025-04-08 20:23:34 -04:00
|
|
|
// Copyright 2025 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
import * as logging from '../logging/log';
|
|
|
|
|
|
|
|
const MAX_SAFE_TIMEOUT_DELAY = 2147483647; // max 32-bit signed integer
|
|
|
|
|
|
|
|
// Prefer using this function over setTimeout in any circumstances where
|
|
|
|
// the delay is not hardcoded to < MAX_SAFE_TIMEOUT_DELAY. Sets and returns a
|
|
|
|
// timeout if the delay is safe, otherwise does not set a timeout.
|
|
|
|
export function safeSetTimeout(
|
|
|
|
callback: VoidFunction,
|
2025-05-06 00:39:04 +10:00
|
|
|
providedDelayMs: number,
|
|
|
|
options?: {
|
|
|
|
clampToMax: boolean;
|
|
|
|
}
|
2025-04-08 20:23:34 -04:00
|
|
|
): NodeJS.Timeout | null {
|
2025-05-06 00:39:04 +10:00
|
|
|
let delayMs = providedDelayMs;
|
|
|
|
|
|
|
|
if (delayMs < 0) {
|
|
|
|
logging.warn('safeSetTimeout: timeout is less than zero');
|
|
|
|
delayMs = 0;
|
|
|
|
}
|
|
|
|
|
2025-04-08 20:23:34 -04:00
|
|
|
if (delayMs > MAX_SAFE_TIMEOUT_DELAY) {
|
2025-05-06 00:39:04 +10:00
|
|
|
if (options?.clampToMax) {
|
|
|
|
delayMs = MAX_SAFE_TIMEOUT_DELAY;
|
|
|
|
} else {
|
|
|
|
logging.warn(
|
|
|
|
'safeSetTimeout: timeout is larger than maximum setTimeout delay'
|
|
|
|
);
|
|
|
|
return null;
|
|
|
|
}
|
2025-04-08 20:23:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return setTimeout(callback, delayMs);
|
|
|
|
}
|