| 1 | /** Async function that waits for specified number of time units. */ |
| 2 | export async function sleep(miliseconds = 0, seconds = 0, minutes = 0, hours = 0, days = 0) { |
| 3 | hours += days * 24; |
| 4 | minutes += hours * 60; |
| 5 | seconds += minutes * 60; |
| 6 | miliseconds += seconds * 1000; |
| 7 | |
| 8 | // Maximum safe timeout is 1 hour (in milliseconds) |
| 9 | const MAX_TIMEOUT = 60 * 60 * 1000; |
| 10 | |
| 11 | // if miliseconds is 0, wait at least one frame |
| 12 | if (miliseconds === 0) { |
| 13 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 14 | return; |
| 15 | } |
| 16 | |
| 17 | // If the timeout is too large, break it into smaller chunks |
| 18 | while (miliseconds > 0) { |
| 19 | // Calculate the current chunk duration (1 hour max) |
| 20 | const chunkDuration = Math.min(miliseconds, MAX_TIMEOUT); |
| 21 | |
| 22 | // Wait for the current chunk |
| 23 | await new Promise((resolve) => setTimeout(resolve, chunkDuration)); |
| 24 | |
| 25 | // Subtract the time we've waited |
| 26 | miliseconds -= chunkDuration; |
| 27 | } |
| 28 | } |
| 29 | export default sleep; |
| 30 | |
| 31 | /** Equals to Sleep(0), but can be used to yield break a coroutine after N interations. */ |
| 32 | let yieldIterations = 0; |
| 33 | export async function Yield(afterIterations = 1) { |
| 34 | yieldIterations++; |
| 35 | if (yieldIterations >= afterIterations) { |
| 36 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 37 | yieldIterations = 0; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /** Awaits equivalent of Sleep(0) N times which means it skips N-1 turns in the eventQueue. */ |
| 42 | export async function Skip(turns = 1) { |
| 43 | while (turns > 0) { |
| 44 | await new Promise((resolve) => setTimeout(resolve, 0)); |
| 45 | turns--; |
| 46 | } |
| 47 | } |