Skip to content

[Bug]: setTimeout/setInterval return timer ID 0 for first timer, colliding with no-op sentinel #5378

@iammdzaidalam

Description

@iammdzaidalam

Problem

IntervalInnerState::next_id() returns the internal counter before incrementing it. The counter starts at 0 via Default, so the first valid timer gets handle 0:

// core/runtime/src/interval.rs:38-44
fn next_id(&mut self) -> JsResult<u32> {
    self.active_map.retain(|_, v| !v.revoked());
    let id = self.id;       // 0 on first call
    self.id = id.checked_add(1)...;
    Ok(id)                  // returns 0
}

Both set_timeout (L68) and set_interval (L123) return Ok(0) as a sentinel when no callback is provided:

let Some(function_ref) = function_ref else {
    return Ok(0);
};

The first real timer and the "nothing was scheduled" sentinel are now indistinguishable. This violates WHATWG HTML §8.6 Timers, which requires timer handles to be positive integers, and breaks the ubiquitous if (timer) clearTimeout(timer) idiom for the first timer in a context.

Reproduction (main at d2caa75c):

cargo run -p boa_cli -- -e \
  "console.log(setTimeout(() => {}, 10)); \
   console.log(setTimeout(() => {}, 10)); \
   console.log(setTimeout())"
0     ← first valid timer (should be > 0)
1
0     ← no-callback sentinel (collides)

Root Cause

Introduced in 8820b777 (#5289). The pre-refactor code incremented before returning, so the first ID was always 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions