Skip to content

Commit f30a10b

Browse files
hyperlinkdarrachequesne
authored andcommitted
fix(websocket): fix timer blocking writes (#670)
An immediate setTimeout was used to unblock the WebSocket write. Unfortunately, this setTimeout can be throttled by browsers when the tab is backgrounded. This can lead to missed pong responses to server pings, which eventually leads to disconnection. Related: #649
1 parent 52847fd commit f30a10b

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
const globalThis = require("../globalThis");
2+
const nextTick = (() => {
3+
const isPromiseAvailable =
4+
typeof Promise === "function" && typeof Promise.resolve === "function";
5+
if (isPromiseAvailable) {
6+
return cb => Promise.resolve().then(cb);
7+
} else {
8+
return cb => setTimeout(cb, 0);
9+
}
10+
})();
211

312
module.exports = {
413
WebSocket: globalThis.WebSocket || globalThis.MozWebSocket,
514
usingBrowserWebSocket: true,
6-
defaultBinaryType: "arraybuffer"
15+
defaultBinaryType: "arraybuffer",
16+
nextTick
717
};
+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module.exports = {
22
WebSocket: require("ws"),
33
usingBrowserWebSocket: false,
4-
defaultBinaryType: "nodebuffer"
4+
defaultBinaryType: "nodebuffer",
5+
nextTick: process.nextTick
56
};

lib/transports/websocket.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ const { pick } = require("../util");
66
const {
77
WebSocket,
88
usingBrowserWebSocket,
9-
defaultBinaryType
9+
defaultBinaryType,
10+
nextTick
1011
} = require("./websocket-constructor");
1112

1213
const debug = require("debug")("engine.io-client:websocket");
@@ -161,10 +162,10 @@ class WS extends Transport {
161162
if (lastPacket) {
162163
// fake drain
163164
// defer to next tick to allow Socket to clear writeBuffer
164-
setTimeout(() => {
165+
nextTick(() => {
165166
this.writable = true;
166167
this.emit("drain");
167-
}, 0);
168+
});
168169
}
169170
});
170171
}

0 commit comments

Comments
 (0)