mobility-toolbox-js
Version:
Toolbox for JavaScript applications in the domains of mobility and logistics.
31 lines (30 loc) • 1.16 kB
JavaScript
/**
* This function returns a WebSocket api callback, and call the onUpdate function with the list of of subscribed objects changes.
*
* @param {function(objects: any[])} onUpdate callback when list of subscribed objects changes, called after 100 ms
* @param {function(object: any)} [getObjectId = true] function returning the id of an object
* @param {number} [timeout = 100] debounce timeout in ms
* @private
*/
const debounceWebsocketMessages = (onUpdate, getObjectId, timeout = 100) => {
const updateTimeout = {};
const objectsById = {};
const objects = [];
return (data) => {
const { content, source } = data;
if (updateTimeout[source]) {
window.clearTimeout(updateTimeout[source]);
}
if (getObjectId) {
objectsById[getObjectId(content)] = content;
}
else {
objects.push(content);
}
updateTimeout[source] = window.setTimeout(() => {
const objectToReturn = getObjectId ? Object.values(objectsById) : objects;
onUpdate(objectToReturn);
}, timeout);
};
};
export default debounceWebsocketMessages;