topkat-utils
Version:
A comprehensive collection of TypeScript/JavaScript utility functions for common programming tasks. Includes validation, object manipulation, date handling, string formatting, and more. Zero dependencies, fully typed, and optimized for performance.
90 lines (88 loc) • 3.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.perfTimer = exports.retryWithDelay = exports.executeInDelayedLoop = exports.waitUntilTrue = exports.runAsync = exports.timeout = void 0;
//----------------------------------------
// TIMEOUT UTILS
//----------------------------------------
const logger_utils_1 = require("./logger-utils");
const error_utils_1 = require("./error-utils");
const math_utils_1 = require("./math-utils");
async function timeout(ms, fn = () => { }) { return new Promise(res => setTimeout(res, ms)).then(fn); }
exports.timeout = timeout;
async function runAsync(callback, milliseconds$ = 1) { return timeout(milliseconds$, callback); }
exports.runAsync = runAsync;
/**
*
* @param {Function} callback function that shall return ===true asynchronously
* @param {Number} timeoutSec default:10; general timeout in seconds
* @param {Boolean|String} errorAfterNSeconds default:true output an error in case of timeout, can be the displayed error message
* @param {*} cliOutput write a cli progress to show that a process is running
*/
async function waitUntilTrue(callback, timeoutSec = 10, errorAfterNSeconds = true, cliOutput = true) {
let generalTimeout = true;
let step = 3;
const errMess = typeof errorAfterNSeconds === 'string' ? 'Timeout: ' + errorAfterNSeconds : 'Timeout for waitUntilTrue() callback';
if (timeoutSec)
setTimeout(() => generalTimeout = false, timeoutSec * 1000);
while (callback() !== true && generalTimeout) {
if (cliOutput)
(0, logger_utils_1.cliProgressBar)(step++);
await timeout(300);
}
if (cliOutput)
process.stdout.write(`\n`);
if (!generalTimeout && errorAfterNSeconds)
throw new error_utils_1.DescriptiveError(errMess, { code: 500 });
}
exports.waitUntilTrue = waitUntilTrue;
const delayedLoopParams = [];
let isExecuting = false;
/** Allow to perform an action in a delayed loop, useful for example to avoid reaching limits on servers. This function can be securely called multiple times.
* @param {Function} callback
* @param {Number} time default: 500ms;
* @param {Function} errorCallback default: e => C.error(e)
*/
async function executeInDelayedLoop(callback, time = 500, errorCallback = (e) => logger_utils_1.C.error(e)) {
delayedLoopParams.push([callback, time, errorCallback]);
if (isExecuting)
return;
isExecuting = true;
while (delayedLoopParams.length) {
const [callback, time, errorCallback] = delayedLoopParams.shift();
try {
await callback();
await timeout(time);
}
catch (err) {
errorCallback(err);
}
}
isExecuting = false;
}
exports.executeInDelayedLoop = executeInDelayedLoop;
/** Will first wait before calling callback every seconds configured in retrySeconds array */
async function retryWithDelay(callback, retrySeconds) {
for (const n of retrySeconds) {
await timeout(n * 1000);
await callback();
}
}
exports.retryWithDelay = retryWithDelay;
/** Use this timer to measure code performances.
* @example ```typescript
const time = perfTimer()
for(let i = 0; i < 9999;i++) longProcess()
console.log('Process took ' + time.end())
```
*/
function perfTimer(unit = 'seconds') {
return {
start: Date.now(),
end() {
const msSinceStart = Date.now() - this.start;
return unit === 'ms' ? msSinceStart + ' ' + unit : (0, math_utils_1.round2)(msSinceStart / 1000) + ' ' + unit;
}
};
}
exports.perfTimer = perfTimer;
//# sourceMappingURL=timer-utils.js.map