diff --git a/packages/ws/src/ws/WebSocketShard.ts b/packages/ws/src/ws/WebSocketShard.ts index b0c67a02ff94..5671a69b28ff 100644 --- a/packages/ws/src/ws/WebSocketShard.ts +++ b/packages/ws/src/ws/WebSocketShard.ts @@ -128,10 +128,26 @@ export class WebSocketShard extends AsyncEventEmitter { } public async connect() { - const promise = this.initialConnectResolved ? Promise.resolve() : once(this, WebSocketShardEvents.Ready); + const controller = new AbortController(); + let promise; + + if (!this.initialConnectResolved) { + // Sleep for the remaining time, but if the connection closes in the meantime, we shouldn't wait the remainder to avoid blocking the new conn + promise = Promise.race([ + once(this, WebSocketShardEvents.Ready, { signal: controller.signal }), + once(this, WebSocketShardEvents.Resumed, { signal: controller.signal }), + ]); + } + void this.internalConnect(); - await promise; + try { + await promise; + } finally { + // cleanup hanging listeners + controller.abort(); + } + this.initialConnectResolved = true; }