From 67c0467e5e8fded739eaa38bceb76b4bec929679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexis=20M=C3=A9taireau?= Date: Fri, 25 Oct 2024 16:53:37 +0200 Subject: [PATCH] feat(sync): Only send sync events after one second of inactivity. --- umap/static/umap/js/modules/sync/engine.js | 5 +++-- umap/static/umap/js/modules/utils.js | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/umap/static/umap/js/modules/sync/engine.js b/umap/static/umap/js/modules/sync/engine.js index 061a171a2..33424d334 100644 --- a/umap/static/umap/js/modules/sync/engine.js +++ b/umap/static/umap/js/modules/sync/engine.js @@ -8,6 +8,7 @@ import { WebSocketTransport } from './websocket.js' const RECONNECT_DELAY = 2000; const RECONNECT_DELAY_FACTOR = 2; const MAX_RECONNECT_DELAY = 32000; +const DEBOUNCE_DELAY = 1000; /** * The syncEngine exposes an API to sync messages between peers over the network. @@ -64,6 +65,7 @@ export class SyncEngine { this._reconnectTimeout = null; this._reconnectDelay = RECONNECT_DELAY; this.websocketConnected = false; + this._send = Utils.debounce(this.__send.bind(this), DEBOUNCE_DELAY) } /** @@ -121,10 +123,9 @@ export class SyncEngine { this._send({ verb: 'delete', subject, metadata, key }) } - _send(inputMessage) { + __send(inputMessage) { const message = this._operations.addLocal(inputMessage) - if (this.offline) return if (this.transport) { this.transport.send('OperationMessage', message) } diff --git a/umap/static/umap/js/modules/utils.js b/umap/static/umap/js/modules/utils.js index 3e4517208..c56515dd1 100644 --- a/umap/static/umap/js/modules/utils.js +++ b/umap/static/umap/js/modules/utils.js @@ -430,3 +430,15 @@ export function deepEqual(object1, object2) { export function slugify(str) { return (str || 'data').replace(/[^a-z0-9]/gi, '_').toLowerCase() } + +export function debounce(callback, wait) { + let timeoutId = null; + + return (...args) => { + clearTimeout(timeoutId); + + timeoutId = setTimeout(() => { + callback.apply(null, args); + }, wait); + }; +} \ No newline at end of file