Everyone gets a turn
Interactive systems can't let one job hog the CPU. Round robin gives each ready process a time slice (quantum); when it's used up, a timer interrupt preempts the process and puts it at the back of the queue. Small quanta feel snappy but waste time on context switches.
The queue in motion
function roundRobin(jobs, quantum) {
const pending = [...jobs].sort((a, b) => a.arrival - b.arrival);
const left = Object.fromEntries(jobs.map((j) => [j.id, j.burst]));
const queue = [];
const slices = [];
const finish = {};
let time = 0;
const admit = () => {
while (pending.length && pending[0].arrival <= time) queue.push(pending.shift().id);
};
admit();
while (queue.length || pending.length) {
if (!queue.length) {
time = pending[0].arrival; // idle until the next arrival
admit();
continue;
}
const id = queue.shift();
const run = Math.min(quantum, left[id]);
slices.push([id, time, time + run]);
time += run;
left[id] -= run;
admit(); // newcomers join the queue before the preempted job
if (left[id] > 0) queue.push(id);
else finish[id] = time;
}
return { slices, finish };
}