* Keeps only one active timeout: whichever task is due next.
()
| 48 | * Keeps only one active timeout: whichever task is due next. |
| 49 | */ |
| 50 | private updateTimeout(): void { |
| 51 | if (this.timeoutId !== null) { |
| 52 | clearTimeout(this.timeoutId) |
| 53 | this.timeoutId = null |
| 54 | } |
| 55 | |
| 56 | if (this.tasks.size === 0) { |
| 57 | return |
| 58 | } |
| 59 | |
| 60 | let earliestTime = Infinity |
| 61 | for (const task of this.tasks.values()) { |
| 62 | if (task.executeAt < earliestTime) { |
| 63 | earliestTime = task.executeAt |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | const delay = Math.max(0, earliestTime - Date.now()) |
| 68 | this.timeoutId = setTimeout(() => this.process(), delay) |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Runs every task whose deadline has passed, then schedules the next wakeup |