1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
//! Timer support (`setTimeout` / `setInterval` / `requestAnimationFrame`)
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use boa_engine::JsValue;
use boa_engine::object::JsObject;
use rustc_hash::FxHashSet;
use web_time::{Duration, Instant};
pub(crate) struct Timer {
pub id: u64,
pub deadline: Instant,
/// `Some` for `setInterval` timers, which reschedule themselves.
pub interval: Option<Duration>,
pub callback: JsObject,
pub args: Vec<JsValue>,
/// Frame callbacks receive their timestamp when the frame runs.
pub animation_frame: bool,
}
/// Ordered by deadline, then by id so that two timers due at the same instant
/// fire in the order they were created, as they would in a browser.
///
/// Reversed, because [`BinaryHeap`] is a max-heap and the soonest deadline is
/// the one to pop first.
impl Ord for Timer {
fn cmp(&self, other: &Self) -> Ordering {
other
.deadline
.cmp(&self.deadline)
.then_with(|| other.id.cmp(&self.id))
}
}
impl PartialOrd for Timer {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Timer {
fn eq(&self, other: &Self) -> bool {
self.deadline == other.deadline && self.id == other.id
}
}
impl Eq for Timer {}
/// Pending timers, ordered by deadline.
///
/// Was a `Vec` scanned linearly, so every operation was O(n) including
/// `next_deadline`, which `arm_timer_thread` calls after every `eval`, every UI
/// event and every poll. Draining a queue of n script tasks therefore cost n
/// full scans of every pending timer. A heap makes the scheduling decision O(1)
/// and each pop O(log n).
#[derive(Default)]
pub(crate) struct TimerQueue {
next_id: u64,
timers: BinaryHeap<Timer>,
/// Ids that are still scheduled.
///
/// Removing from the middle of a heap means rebuilding it, so cancellation
/// is lazy: `remove` drops the id here and the heap entry is skipped when
/// it surfaces. Tracking what is live rather than what was cancelled keeps
/// this the size of the pending set, so cancelling an id that already fired
/// costs nothing and retains nothing.
live: FxHashSet<u64>,
}
impl TimerQueue {
pub fn add(
&mut self,
delay: Duration,
interval: Option<Duration>,
callback: JsObject,
args: Vec<JsValue>,
) -> u64 {
self.add_timer(delay, interval, callback, args, false)
}
pub fn add_animation_frame(&mut self, callback: JsObject) -> u64 {
// Approximate the next frame as ~16ms away.
self.add_timer(Duration::from_millis(16), None, callback, Vec::new(), true)
}
fn add_timer(
&mut self,
delay: Duration,
interval: Option<Duration>,
callback: JsObject,
args: Vec<JsValue>,
animation_frame: bool,
) -> u64 {
self.next_id += 1;
let id = self.next_id;
self.live.insert(id);
self.timers.push(Timer {
id,
deadline: Instant::now() + delay,
interval,
callback,
args,
animation_frame,
});
id
}
pub fn remove(&mut self, id: u64) {
if !self.live.remove(&id) {
return;
}
self.discard_dead_front();
}
/// Claim a frame callback immediately before invoking it.
///
/// Due frame callbacks remain cancellable while earlier callbacks run.
/// Removing the id here also makes cancellation after invocation a no-op.
pub fn begin_animation_frame_callback(&mut self, id: u64) -> bool {
self.live.remove(&id)
}
/// The deadline of the timer which is due soonest (if any).
///
/// The front is always a live timer: every mutation discards dead entries
/// that reach it. Without that the event loop would arm a wakeup for a
/// timer that has been cancelled and will never run.
pub fn next_deadline(&self) -> Option<Instant> {
self.timers.peek().map(|timer| timer.deadline)
}
/// Remove and return all timers that are due at `now`, soonest first.
/// Interval timers are rescheduled.
///
/// Frame callback ids stay live until invocation so an earlier callback
/// can cancel a later callback from this snapshot.
pub fn take_due(&mut self, now: Instant) -> Vec<Timer> {
let mut due: Vec<Timer> = Vec::new();
while let Some(timer) = self.timers.peek() {
if timer.deadline > now {
break;
}
let timer = self.timers.pop().expect("peeked");
if !self.live.contains(&timer.id) {
continue;
}
match timer.interval {
// Rescheduled before the callback runs, and never at `now`
// itself, so an interval cannot be collected twice by one
// drain. The id stays live so `clearInterval` still reaches it.
Some(interval) => self.timers.push(Timer {
id: timer.id,
deadline: now + interval.max(Duration::from_millis(1)),
interval: timer.interval,
callback: timer.callback.clone(),
args: timer.args.clone(),
animation_frame: timer.animation_frame,
}),
None if timer.animation_frame => {}
None => {
self.live.remove(&timer.id);
}
}
due.push(timer);
}
self.discard_dead_front();
due
}
/// Drop cancelled entries that have reached the front of the heap, so that
/// [`next_deadline`](Self::next_deadline) never reports one.
fn discard_dead_front(&mut self) {
while let Some(timer) = self.timers.peek() {
if self.live.contains(&timer.id) {
return;
}
self.timers.pop();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use boa_engine::Context;
/// Timers hold a JS callback, but none of the ordering or cancellation
/// logic touches it, so any object stands in.
fn callback(context: &mut Context) -> JsObject {
JsObject::with_object_proto(context.intrinsics())
}
#[test]
fn the_soonest_deadline_is_the_one_reported() {
let mut context = Context::default();
let mut queue = TimerQueue::default();
queue.add(
Duration::from_millis(500),
None,
callback(&mut context),
Vec::new(),
);
let near = Instant::now() + Duration::from_millis(10);
queue.add(
Duration::from_millis(10),
None,
callback(&mut context),
Vec::new(),
);
queue.add(
Duration::from_millis(900),
None,
callback(&mut context),
Vec::new(),
);
let deadline = queue.next_deadline().expect("three timers are pending");
assert!(
deadline <= near + Duration::from_millis(5),
"the heap must surface the nearest deadline, not the first inserted"
);
}
#[test]
fn same_deadline_fires_in_creation_order() {
let mut context = Context::default();
let mut queue = TimerQueue::default();
let first = queue.add(
Duration::from_millis(0),
None,
callback(&mut context),
Vec::new(),
);
let second = queue.add(
Duration::from_millis(0),
None,
callback(&mut context),
Vec::new(),
);
let due = queue.take_due(Instant::now() + Duration::from_millis(1));
let ids: Vec<u64> = due.iter().map(|timer| timer.id).collect();
assert_eq!(ids, vec![first, second]);
}
#[test]
fn a_cancelled_timeout_never_runs_and_stops_arming_the_loop() {
let mut context = Context::default();
let mut queue = TimerQueue::default();
let id = queue.add(
Duration::from_millis(0),
None,
callback(&mut context),
Vec::new(),
);
queue.remove(id);
assert!(
queue.next_deadline().is_none(),
"a cancelled timer must not keep waking the event loop"
);
assert!(queue.take_due(Instant::now()).is_empty());
}
#[test]
fn an_interval_reschedules_until_cancelled() {
let mut context = Context::default();
let mut queue = TimerQueue::default();
let id = queue.add(
Duration::from_millis(0),
Some(Duration::from_millis(1)),
callback(&mut context),
Vec::new(),
);
let now = Instant::now() + Duration::from_millis(1);
assert_eq!(queue.take_due(now).len(), 1);
assert!(
queue.next_deadline().is_some(),
"an interval reschedules itself"
);
queue.remove(id);
assert!(
queue.next_deadline().is_none(),
"clearInterval has to reach the rescheduled copy"
);
}
#[test]
fn cancelling_an_id_that_already_fired_retains_nothing() {
let mut context = Context::default();
let mut queue = TimerQueue::default();
let id = queue.add(
Duration::from_millis(0),
None,
callback(&mut context),
Vec::new(),
);
// A long-lived interval keeps the heap non-empty, which is the case
// where a set of cancelled ids would grow without bound.
queue.add(
Duration::from_secs(30),
Some(Duration::from_secs(30)),
callback(&mut context),
Vec::new(),
);
assert_eq!(queue.take_due(Instant::now()).len(), 1);
for _ in 0..1_000 {
queue.remove(id);
}
assert_eq!(
queue.live.len(),
1,
"only the pending interval is tracked: {:?}",
queue.live
);
}
}