Goal: distinguish scheduling from execution
Implement timer registration separately from callback execution in Rust. Calling setTimeout records a handle, deadline, and function name; it does not enter that function immediately. The current script continues. Compare the timer list with the call stack and locate a state where a function is pending without being an active call. This distinction is the starting point for reasoning about deferred work.
The project is examples/rust-browser-wave5. call_async_builtin registers work, while run_next_task selects a runnable timer. Both native execution and WASM use the same bounded Rust interpreter. The host JavaScript timer API does not execute the input program, so an identical input and operation sequence can reproduce the same scheduling decisions in both builds.
Use an explicit virtual clock
Here clock is an educational timestamp measured in milliseconds. Advancing it changes eligibility; running the next task selects one eligible callback. Moving the clock by ten milliseconds is an explicit input operation, not a request to wait ten milliseconds on the host. This separation lets you stop just before a deadline, inspect the state, and then cross the boundary deliberately.
A real browser does not promise an exact execution time for a requested delay. This project removes timing variability to isolate eligibility and selection. It does not model CPU contention or browser background throttling and is not a browser performance benchmark. Check three separate events: reaching a deadline, selecting a task, and finishing its callback.
Store deadlines and cancellation handles
This subset accepts declared, zero-argument named functions. Code strings, arrow functions, and additional callback arguments are outside its contract. Delays must be finite numbers. Negative delays become zero and fractional values are truncated to integer milliseconds. A deadline is the current clock plus that normalized delay; exceeding the bounded clock produces a diagnostic rather than arithmetic wraparound.
The returned numeric handle identifies one registration. clearTimeout removes that registration rather than removing every timer with the same callback name. Compare cancelling an existing handle with cancelling it again after removal. Neither operation should affect an unrelated timer. The history records whether a matching registration was present, which helps explain an apparently missing callback.
Worked example: cancel at five, execute at ten
Enter this code into the Rust task demo or the distributed CLI with --async. The initial script prints script. The five-millisecond callback is cancelled before execution and never prints cancelled. At clock ten the remaining callback is eligible, but it still has not run until a runNext operation selects it. One such operation then prints timer.
For the CLI, place the program in a JSON envelope with schemaVersion:1, html, css, javascript, and operations. Use [{"type":"advance","milliseconds":10},{"type":"runNext"}] to reproduce the clock change followed by selection. Compare initialization, just before the deadline, eligibility, and completion. Explain each change through a consumed operation and Rust branch rather than elapsed host time.
function later() { console.log("timer"); }
function cancelled() { console.log("cancelled"); }
let first = setTimeout(later, 10);
let second = setTimeout(cancelled, 5);
clearTimeout(second);
console.log("script");| State after operation | ID1 / due10 | ID2 / due5 | Eligible next timer |
|---|---|---|---|
| Initial script ends | Pending | Cancelled | None(clock=0) |
| advance9 | Pending | Cancelled | None |
| advance1 | Pending and eligible | Cancelled | ID1 |
| runNext | Consumed | Cancelled | None |
Separate normal, boundary, and rejected inputs
For a normal case, execute one timer due at ten. For a boundary case, compare clocks nine and ten. A zero delay still does not interrupt the script that registered it. Inspect the stored nesting value in a chain of timers: deeply nested timers can receive a four-millisecond minimum delay. In that case inspect the resulting deadline instead of assuming that a requested zero simply adds nothing.
Try an unknown callback, a callback requiring arguments, and a nonnumeric delay as rejected inputs. Separate these diagnostics from a successful cancellation or an empty runnable set. Limits also bound total registrations, pending callbacks, operations, and the clock. A resource-limit test asks whether execution terminates predictably, whereas an invalid-argument test asks whether the API contract was checked.
Runnable Rust: selection and cancellation
This standalone Rust program tests two small contracts: a timer is ineligible before its deadline, and a removed timer cannot be selected. Compile it as one file with rustc. It does not parse JavaScript or evaluate function bodies. Isolating the selection rule makes it easier to compare the actual run_next_task implementation with a precise expected behavior.
Notice that storage order and execution order are separate. Select by deadline and then handle. Removing one vector element can change positions without changing other handles, so a handle must not silently become a vector index. The full CLI also drains microtasks and records a rendering opportunity after a task; passing this smaller contract is not proof of the entire interpreter.
#[derive(Clone, Debug)]
struct Timer { id: u64, due: u64, name: &'static str }
fn next(timers: &[Timer], now: u64) -> Option<usize> {
timers.iter().enumerate().filter(|(_, t)| t.due <= now)
.min_by_key(|(_, t)| (t.due, t.id)).map(|(i, _)| i)
}
fn main() {
let mut timers = vec![Timer{id:1,due:10,name:"later"},
Timer{id:2,due:5,name:"cancelled"}];
timers.retain(|t| t.id != 2);
assert_eq!(next(&timers, 9), None);
let i = next(&timers, 10).unwrap();
assert_eq!(timers.remove(i).name, "later");
assert!(timers.is_empty());
println!("before=none at10=later cancelled=absent");
}Connect source branches to observable state
In call_async_builtin, follow argument validation, function lookup, deadline calculation, and handle allocation. Then locate the due <= clock condition in run_next_task. Observe where the selected timer is removed before its callback runs. If that callback registers another timeout, explain why it creates a new registration rather than reusing the consumed task implicitly.
The interface reproduces state from initial input plus its saved operations. Resuming does not restore a host timer. Compare clock, pending registrations, and history after replay to determine whether the saved state is sufficient. Match the source version to the distributed WASM version so that outputs from different implementations are not mistaken for inconsistent runs of one build.
Exercise: make a delayed display cancellable
Create a button that schedules a display update ten milliseconds later and a second action that cancels it. Decide which binding stores the handle and how you represent the absence of a pending registration. Perform clicks, clock advances, and task execution separately. Record both the pending count and displayed text before and after cancellation.
Submit the handle, cancellation time, and task-selection time. Then schedule the same function for five and ten milliseconds and cancel one registration. Explain why identical callback names still identify different reservations. Check cancellation after eligibility but before selection, and finish by distinguishing a scheduling order guarantee from a promise about wall-clock execution.