Skip to content

Commit 89eebc4

Browse files
committed
Incorrect implementation of .setTimeout - with fix #194
1 parent 7b548ae commit 89eebc4

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/Socket.js

+12-11
Original file line numberDiff line numberDiff line change
@@ -182,26 +182,27 @@ export default class Socket extends EventEmitter {
182182
* @param {() => void} [callback]
183183
*/
184184
setTimeout(timeout, callback) {
185-
if (timeout === 0) {
185+
this._timeoutMsecs = timeout;
186+
if (this._timeoutMsecs === 0) {
186187
this._clearTimeout();
187188
} else {
188-
this._activateTimer(timeout);
189+
this._resetTimeout();
189190
}
190191
if (callback) this.once('timeout', callback);
191192
return this;
192193
}
193194

194195
/**
195196
* @private
196-
* @param {number} [timeout]
197197
*/
198-
_activateTimer(timeout) {
199-
if (timeout !== undefined) this._timeoutMsecs = timeout;
200-
this._clearTimeout();
201-
this._timeout = setTimeout(() => {
198+
_resetTimeout() {
199+
if (this._timeoutMsecs !== 0) {
202200
this._clearTimeout();
203-
this.emit('timeout');
204-
}, this._timeoutMsecs);
201+
this._timeout = setTimeout(() => {
202+
this._clearTimeout();
203+
this.emit('timeout');
204+
}, this._timeoutMsecs);
205+
}
205206
}
206207

207208
/**
@@ -327,7 +328,6 @@ export default class Socket extends EventEmitter {
327328
* @return {boolean}
328329
*/
329330
write(buffer, encoding, cb) {
330-
const self = this;
331331
if (this._pending || this._destroyed) throw new Error('Socket is closed.');
332332

333333
const generatedBuffer = this._generateSendBuffer(buffer, encoding);
@@ -340,7 +340,7 @@ export default class Socket extends EventEmitter {
340340
this._msgEvtEmitter.removeListener('written', msgEvtHandler);
341341
this._writeBufferSize -= generatedBuffer.byteLength;
342342
this._lastRcvMsgId = msgId;
343-
if (self._timeout) self._activateTimer();
343+
this._resetTimeout();
344344
if (this.writableNeedDrain && this._lastSentMsgId === msgId) {
345345
this.writableNeedDrain = false;
346346
this.emit('drain');
@@ -434,6 +434,7 @@ export default class Socket extends EventEmitter {
434434
*/
435435
_onDeviceDataEvt = (/** @type {{ id: number; data: string; }} */ evt) => {
436436
if (evt.id !== this._id) return;
437+
this._resetTimeout();
437438
if (!this._paused) {
438439
const bufferData = Buffer.from(evt.data, 'base64');
439440
this._bytesRead += bufferData.byteLength;

0 commit comments

Comments
 (0)