Last active
March 30, 2025 12:27
-
-
Save leihuang23/1e0dfed84db4264424926dc0b9bd88d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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