Skip to content

Commit 19d55b2

Browse files
authored
Update client.js
use setTimeout and unref timer to avoid memory leaks
1 parent e342bde commit 19d55b2

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/y-socket-io/client.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ export class SocketIOProvider extends Observable {
141141
this.roomName = roomName
142142
this.doc = doc
143143
this.awareness = awareness
144+
this.released = false
144145

145146
this._broadcastChannel = `${url}/${roomName}`
146147
this.disableBc = disableBc
@@ -318,17 +319,20 @@ export class SocketIOProvider extends Observable {
318319
])
319320
)
320321
}
322+
const timeout = () => {
323+
if (this.released) return
324+
if (this.socket.disconnected) return
325+
this.socket.emit(
326+
'sync-step-1',
327+
Y.encodeStateVector(this.doc),
328+
(/** @type {Uint8Array} */ update) => {
329+
Y.applyUpdate(this.doc, new Uint8Array(update), this)
330+
}
331+
)
332+
setTimeout(timeout, resyncInterval)
333+
}
321334
if (resyncInterval > 0) {
322-
this.resyncInterval = setInterval(() => {
323-
if (this.socket.disconnected) return
324-
this.socket.emit(
325-
'sync-step-1',
326-
Y.encodeStateVector(this.doc),
327-
(/** @type {Uint8Array} */ update) => {
328-
Y.applyUpdate(this.doc, new Uint8Array(update), this)
329-
}
330-
)
331-
}, resyncInterval)
335+
setTimeout(timeout, resyncInterval)
332336
}
333337
}
334338

@@ -377,7 +381,7 @@ export class SocketIOProvider extends Observable {
377381
* @type {() => void}
378382
*/
379383
destroy () {
380-
if (this.resyncInterval != null) clearInterval(this.resyncInterval)
384+
this.released = true
381385
this.disconnect()
382386
if (typeof window !== 'undefined') { window.removeEventListener('beforeunload', this.beforeUnloadHandler) } else if (typeof process !== 'undefined') { process.off('exit', this.beforeUnloadHandler) }
383387
this.awareness.off('update', this.awarenessUpdate)

0 commit comments

Comments
 (0)