sleep.js update
frdel committed
Aug 14, 2025 at 13:17 UTC
17e896b697727200933db7c21b4e296961e51b94
1 file changed
+44
-24
webui/js/sleep.js
+44
-24
@@ -1,27 +1,47 @@
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
- await new Promise((resolve) => setTimeout(resolve, miliseconds));
8
- }
9
- export default sleep;
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
11
- /** Equals to Sleep(0), but can be used to yield break a coroutine after N interations. */
12
- let yieldIterations = 0;
13
- export async function Yield(afterIterations = 1) {
14
- yieldIterations++;
15
- if (yieldIterations >= afterIterations) {
16
- await new Promise((resolve) => setTimeout(resolve, 0));
17
- yieldIterations = 0;
18
- }
19
- }
8
+ // Maximum safe timeout is 1 hour (in milliseconds)
9
+ const MAX_TIMEOUT = 60 * 60 * 1000;
10
21
- /** Awaits equivalent of Sleep(0) N times which means it skips N-1 turns in the eventQueue. */
22
- export async function Skip(turns = 1) {
23
- while (turns > 0) {
24
- await new Promise((resolve) => setTimeout(resolve, 0));
25
- turns--;
26
- }
27
- }
\ No newline at end of file
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
+}
\ No newline at end of file