Skip to content

Instantly share code, notes, and snippets.

@leihuang23
Last active March 30, 2025 12:27
Show Gist options
  • Save leihuang23/1e0dfed84db4264424926dc0b9bd88d0 to your computer and use it in GitHub Desktop.
Save leihuang23/1e0dfed84db4264424926dc0b9bd88d0 to your computer and use it in GitHub Desktop.
let timeout = null;
const queue = new Set();
function process() {
for (const task of queue) {
task();
}
queue.clear();
timeout = null;
}
function enqueue(task) {
if (timeout === null) timeout = setTimeout(process, 0);
queue.add(task);
}
// Example for batching API calls
const apiClient = {
batchUpdateUsers(updates) {
console.log("API called with updates:", updates);
},
};
const pendingUpdates = {};
function scheduleUserUpdate(userId, fieldName, value) {
if (!pendingUpdates[userId]) {
pendingUpdates[userId] = {};
}
pendingUpdates[userId][fieldName] = value;
if (timeout === null) {
enqueue(() => {
const updates = { ...pendingUpdates };
for (const userId in pendingUpdates) {
delete pendingUpdates[userId];
}
apiClient.batchUpdateUsers(updates);
});
}
}
scheduleUserUpdate("user123", "name", "John Smith");
scheduleUserUpdate("user123", "email", "[email protected]");
scheduleUserUpdate("user456", "status", "active");
/* result:
API called with updates: {
user123: { name: 'John Smith', email: '[email protected]' },
user456: { status: 'active' }
} */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment