Skip to content

Instantly share code, notes, and snippets.

@alpavlove
Created November 28, 2024 07:57
Show Gist options
  • Save alpavlove/1d91bd64db1b0340c6604eed4729580d to your computer and use it in GitHub Desktop.
Save alpavlove/1d91bd64db1b0340c6604eed4729580d to your computer and use it in GitHub Desktop.
const queue = new TaskQueue(2); // Limit concurrency to 2 tasks
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Add tasks to the queue
queue.add(() => sleep(1000).then(() => console.log("Task 1 completed")));
queue.add(() => sleep(500).then(() => console.log("Task 2 completed")));
queue.add(() => sleep(300).then(() => console.log("Task 3 completed")));
queue.add(() => sleep(400).then(() => console.log("Task 4 completed")));
// Expected output (timing may vary):
// Task 1 completed (after ~1000ms)
// Task 2 completed (after ~1000ms)
// Task 3 completed (after ~1300ms)
// Task 4 completed (after ~1400ms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment