Skip to content
File

Blob: src/workerd/api/tests/settimeout-test.js

javascript61 lines
1// Copyright (c) 2026 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4import { ok } from 'node:assert';
5import timers from 'node:timers/promises';
6 
7// Allow up to 10ms of jitter because the precise_timers compat flag
8// can introduce +/-3ms of variance in timer resolution, and coverage
9// builds add additional overhead.
10const JITTER = 10;
11 
12// The first setTimeout was firing too early because
13// kj::Timer::now() was stale after script compilation/startup.
14// Ref: https://github.com/cloudflare/workerd/issues/6019
15export const basicAccuracy = {
16 async test() {
17 const t0 = Date.now();
18 await timers.setTimeout(100);
19 const t1 = Date.now();
20 ok(t1 - t0 >= 100 - JITTER, `Received a difference of ${t1 - t0}`);
21 await timers.setTimeout(100);
22 const t2 = Date.now();
23 ok(t2 - t1 >= 100 - JITTER, `Received a difference of ${t2 - t1}`);
24 },
25};
26 
27// After CPU-heavy work between setTimeout calls,
28// subsequent consecutive setTimeouts must still each wait their full delay
29// rather than all firing at the same instant.
30// Ref: https://github.com/cloudflare/workerd/issues/6037
31export const accuracyAfterCpuWork = {
32 async test() {
33 await timers.setTimeout(50);
34 
35 // Let's burn some CPU
36 for (let j = 0; j < 1e9; j++);
37 
38 const a = Date.now();
39 await timers.setTimeout(50);
40 const b = Date.now();
41 ok(
42 b - a >= 50 - JITTER,
43 `After CPU work, first sleep: expected ~50ms, got ${b - a}ms`
44 );
45 
46 await timers.setTimeout(50);
47 const c = Date.now();
48 ok(
49 c - b >= 50 - JITTER,
50 `After CPU work, second sleep: expected ~50ms, got ${c - b}ms`
51 );
52 
53 await timers.setTimeout(50);
54 const d = Date.now();
55 ok(
56 d - c >= 50 - JITTER,
57 `After CPU work, third sleep: expected ~50ms, got ${d - c}ms`
58 );
59 },
60};