Skip to content

Commit 6a7682c

Browse files
committed
feat: make retransmit timer use setTimeout instead of setInterval #96
This is so that it only runs when packets are inflight, and lowers idle cpu usage
1 parent a4b8a6f commit 6a7682c

File tree

1 file changed

+25
-10
lines changed

1 file changed

+25
-10
lines changed

src/lib/atemSocketChild.ts

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ export class AtemSocketChild {
5252

5353
private _connectionState = ConnectionState.Closed
5454
private _reconnectTimer: NodeJS.Timer | undefined
55-
private _retransmitTimer: NodeJS.Timer | undefined
55+
private _retransmitTimer: NodeJS.Timeout | undefined
5656

5757
private _nextSendPacketId = 1
5858
private _sessionId = 0
@@ -104,14 +104,6 @@ export class AtemSocketChild {
104104
})
105105
}, CONNECTION_RETRY_INTERVAL)
106106
}
107-
// Check for retransmits every 10 milliseconds
108-
if (!this._retransmitTimer) {
109-
this._retransmitTimer = setInterval(() => {
110-
this._checkForRetransmit().catch((e) => {
111-
this.log(`Failed to retransmit: ${e?.message ?? e}`)
112-
})
113-
}, RETRANSMIT_INTERVAL)
114-
}
115107
}
116108

117109
public async connect(address: string, port: number): Promise<void> {
@@ -132,7 +124,7 @@ export class AtemSocketChild {
132124

133125
private _clearTimers() {
134126
if (this._retransmitTimer) {
135-
clearInterval(this._retransmitTimer)
127+
clearTimeout(this._retransmitTimer)
136128
this._retransmitTimer = undefined
137129
}
138130
if (this._reconnectTimer) {
@@ -198,6 +190,7 @@ export class AtemSocketChild {
198190
payload: buffer,
199191
resent: 0,
200192
})
193+
this._triggerRetransmitTimer()
201194
}
202195

203196
private _recreateSocket(): Socket {
@@ -306,6 +299,8 @@ export class AtemSocketChild {
306299
return true
307300
}
308301
})
302+
303+
this._triggerRetransmitTimer()
309304
ps.push(this.onPacketsAcknowledged(ackedCommands))
310305
// this.log(`${Date.now()} Got ack ${ackPacketId} Remaining=${this._inFlight.length}`)
311306
}
@@ -379,8 +374,28 @@ export class AtemSocketChild {
379374
}
380375
}
381376

377+
private _triggerRetransmitTimer(): void {
378+
if (!this._inFlight.length && this._retransmitTimer) {
379+
clearTimeout(this._retransmitTimer)
380+
delete this._retransmitTimer
381+
return
382+
}
383+
384+
if (!this._retransmitTimer) {
385+
this._retransmitTimer = setTimeout(() => {
386+
delete this._retransmitTimer
387+
this._checkForRetransmit().catch((e) => {
388+
this.log(`Failed to retransmit: ${e?.message ?? e}`)
389+
})
390+
}, RETRANSMIT_INTERVAL)
391+
}
392+
}
393+
382394
private async _checkForRetransmit(): Promise<void> {
383395
if (!this._inFlight.length) return
396+
397+
this._triggerRetransmitTimer()
398+
384399
const now = performance.now()
385400
for (const sentPacket of this._inFlight) {
386401
if (sentPacket.lastSent + IN_FLIGHT_TIMEOUT < now) {

0 commit comments

Comments
 (0)