Goal: complete one selected task at a time
Multiple timers require a rule for choosing the next callback. Follow run_next_task as it selects eligible work, invokes one function, and completes its follow-up processing before the next selection. A task is an execution unit that separates current work from work selected later, not merely a function name shown in a panel.
This project models timer-derived tasks and explicit click operations. It does not reproduce every task source or scheduling policy found in a full browser. Its fixed educational policy makes eligibility, equal-deadline ordering, and remaining registrations inspectable by hand without implying universal browser ordering across unrelated sources.
Eligibility differs from being selected next
At clock twenty, timers due at ten and twenty are both eligible. This implementation selects the smallest deadline, then the smallest handle. It does not choose a later deadline merely because that timer was registered first. Compare ready flags with the call stack: multiple eligible registrations do not mean multiple callback bodies execute simultaneously.
One runNext consumes one timer task. A callback may register another timer, but that does not turn the operation into an automatic drain of all future tasks. Small execution units expose callback entry, return, and the following microtask checkpoint. If the pending count stays unchanged, distinguish a newly registered timer from failure to select the original timer.
Reuse the function evaluator inside a task
Selection and function evaluation have different responsibilities. run_next_task chooses a timer and delegates its named callback to call_function. Binding access, returns, argument checks, and invalid DOM references remain the evaluator’s responsibility. Deferred execution does not move the program into host eval or a separate language implementation.
Other timers do not interrupt synchronous statements inside a running callback in this model. If callback A changes a value from one to two, do not invent an interleaving where timer B runs between those assignments. Distinguish operations A performs now from callbacks A merely schedules, and identify where the current call stack becomes empty.
Worked trace: deadlines and handles produce B, C, A
The program initially prints script. Advance the clock to twenty and run the next task three times: the added outputs are B, C, then A. B and C share deadline ten, so their handles break the tie. A was registered first but has deadline twenty. Write the two-part comparison key before running the example.
Use advance20 followed by three runNext operations. Record remaining timers after each, then try a fourth runNext with no pending work. A repeated callback would require investigating removal or an explicit new registration. The table is a prediction aid for running this input, not a fabricated execution log.
function a() { console.log("A"); }
function b() { console.log("B"); }
function c() { console.log("C"); }
setTimeout(a, 20);
setTimeout(b, 10);
setTimeout(c, 10);
console.log("script");| Operation | Added output | Remaining |
|---|---|---|
| Initial script | script | A, B, C |
| advance 20 | none | A, B, C |
| runNext 1 | B | A, C |
| runNext 2 | C | A |
| runNext 3 | A | none |
Boundaries: empty sets, new timers, and failed callbacks
An empty queue and a queue containing only future timers both yield no selected task, but their remaining state differs. Inspect clock and timers rather than inferring both cases from an empty output panel. Add a zero-delay timer inside a callback and confirm that its body waits for another explicit runNext operation.
A selected callback can fail while accessing a missing DOM element. Selection may therefore succeed even when evaluation fails. Match the selection history to the diagnostic within the function. The bounded runtime does not reproduce every detail of browser exception reporting and subsequent continuation; inspect returned frames to determine how far the actual execution progressed.
Runnable Rust: isolate the ordering contract
This standalone program represents each timer by a handle, deadline, and display name. It selects nothing at nine and produces BCA at twenty. Compile it with rustc. It deliberately omits clock advancement, JavaScript evaluation, microtasks, and rendering, which require separate checks against the real distributed project.
Predict the consequence of reversing the comparison key so the handle comes first. Then swap only the handles of B and C while keeping their equal deadlines. A change to selection must preserve both ineligibility before a deadline and consumption after selection, not merely a final output string for one convenient input.
fn take_due(queue: &mut Vec<(u64,u64,char)>, now: u64) -> Option<char> {
let i = queue.iter().enumerate().filter(|(_,t)| t.1 <= now)
.min_by_key(|(_,t)| (t.1,t.0)).map(|(i,_)| i)?;
Some(queue.remove(i).2)
}
fn main() {
let mut queue = vec![(1,20,'A'),(2,10,'B'),(3,10,'C')];
assert_eq!(take_due(&mut queue,9),None);
let order: String = (0..3).filter_map(|_|take_due(&mut queue,20)).collect();
assert_eq!(order,"BCA");
assert_eq!(take_due(&mut queue,20),None);
println!("order={order} remaining={}",queue.len());
}Build reproducible reports from input and operations
Keep the initial HTML, CSS, JavaScript, and operations together. Saying that B ran first does not reveal the clock, cancellation history, or deadlines. Pair the recorded task name and timestamp with the input to reduce a failure to its smallest reproducing sequence. A deterministic clock makes these conditions explicit.
Pass identical JSON to native and WASM builds and compare clock, timers, taskHistory, and diagnostics. Matching visible text can hide different pending work that diverges on the next operation. Conversely, equal runtime state with different presentation points toward frame selection or rendering in the interface. Narrowing the compared boundary helps locate the responsible component.
For a concrete resume check, advance to twenty and consume B, then save. Replaying that sequence must leave A and C pending. Moving the visible frame cursor back to B does not register B again: the operation list defines execution, whereas the cursor selects which already computed state to inspect. Compare the next selected callback after resume with the uninterrupted run. This catches a player that accidentally treats a historical frame as a new initial runtime state, even when its screenshot looks correct.
Exercise: reveal equal-deadline ordering
Prepare two callbacks sharing a deadline and a third callback with another deadline. Separate experiments that change registration order from experiments that change deadlines. After each operation, copy the remaining timers and predict the next selection before executing it. Include a runNext operation while a future registration remains ineligible.
Design a minimal counterexample for a bug that compares handles before deadlines. Explain why an input whose deadlines are all equal cannot expose that bug. Finally add a callback that schedules another timer, and mark the completion of the current task separately from the start of the new one in the trace.