Skip to content

Instantly share code, notes, and snippets.

@rojakcoder
Last active August 19, 2024 07:48
Show Gist options
  • Select an option

  • Save rojakcoder/28d6c0d4d7c7a7d37cdcc38e25a04c95 to your computer and use it in GitHub Desktop.

Select an option

Save rojakcoder/28d6c0d4d7c7a7d37cdcc38e25a04c95 to your computer and use it in GitHub Desktop.
/**
* This function is a placeholder to simulate an AJAX call to the server.
*
* It is able to wait for the specified amount of time, with an option to randomly fail for simulation purposes.
*
* @param timeout - The time in milliseconds to wait before returning control.
* @param probability - The percentage likelihood of this function returning the expected outcome. Value has to be between 0 and 1, otherwise, the value is ignored. The higher the value, the more likely it is to happen. Optional. If not specified, this function will always resolve.
* @param result - The return payload for a success simulation. Optional.
*/
export async function delay<T>(
timeout: number,
probability?: number,
result?: T
): Promise<T> {
return new Promise<T>((resolve, reject) => {
setTimeout(() => {
if (!probability || probability < 0 || probability > 1) {
resolve(result);
return;
}
const hit = Math.random();
if (hit < probability) {
resolve(result);
} else {
reject(
`Placeholder rejection (${Math.round(
hit * 100
)}%) - this should NOT appear in production`
);
}
}, timeout);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment