Skip to content

Instantly share code, notes, and snippets.

@Setitch
Created November 17, 2022 16:23
Show Gist options
  • Save Setitch/4f689a2529d0ced44d10f10f26670bbd to your computer and use it in GitHub Desktop.
Save Setitch/4f689a2529d0ced44d10f10f26670bbd to your computer and use it in GitHub Desktop.
Time Attack Mittigator - function that exeutes the job, with minimum time needed for answer, even if the job finished earlier
/**
* This function will execute the job, but return the value from it when at least `timeout` amount of milliseconds passed
* @param {() => Promise<T>} job
* @param {number} timeout
* @returns {Promise<T>}
*/
export async function TimeAttackMitigator<T>(job: () => Promise<T>, timeout = 700): Promise<T> {
return new Promise<T>((resolve, reject) => {
let canResolve = false;
let state: boolean | undefined;
let value: T;
let error: any;
const tryFinish = () => {
if (canResolve) {
if (state === true) {
canResolve = false;
resolve(value);
} else if (state === false) {
canResolve = false;
reject(error);
}
}
};
setTimeout(() => {
canResolve = true;
tryFinish();
}, timeout);
job().then((arg: T) => {
state = true;
value = arg;
tryFinish();
}).catch((err) => {
state = false;
error = err;
tryFinish();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment