Last active
August 19, 2024 07:48
-
-
Save rojakcoder/28d6c0d4d7c7a7d37cdcc38e25a04c95 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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