In a CodeSOD column, Remy Porter recounts how Karen, a developer maintaining TypeScript specification tests, tracked down a rare but persistent flakiness. The functional, specification-based tests failed roughly three or four times per thousand runs, while the unit tests passed consistently. The operations were timing-sensitive, and the tests already used generous timing windows, so the cause was not obvious.
At several points the tests needed to wait at least two milliseconds. The original helper was the idiomatic one-liner:
```typescript export const wait = (ms:number) => new Promise((complete) => setTimeout(complete, ms)); ```
Standard JavaScript documentation warns that `setTimeout` may wait longer than the requested delay, which Karen accepted. The Node.js documentation, however, makes no guarantee about when the callback is invoked, meaning the timer can fire before the elapsed time.
After extensive debugging, Karen found that the early firings were indeed causing the failures. She replaced the simple helper with this polling version:
```typescript export const wait = (ms: number) { const target = performance.now() + ms; return new Promise((complete) => { const checkReady = () => { if (performance.now() > target) { complete(); } else { setTimeout(checkReady, 1); } } setTimeout(checkReady, 1); }); } ```
This checks the time every millisecond and only resolves once the target duration has actually passed. The change stabilizes the tests, but the author notes the workaround is regrettable: it exists only because Node.js breaks the scheduling guarantee that other runtimes typically honor—waiting at least as long as requested, though possibly much longer.
Comments
No comments yet — be the first.
Open the discussion
No account or password needed — just enter your e-mail and we’ll send you a one-time sign-in link. First time here? You’re set up automatically.
Your rating will be applied automatically after you sign in.
Check your inbox
We’ve sent a sign-in link to …. Open it on this device — this tab will sign you in automatically.
Nothing arrived? Check your spam folder — and mark the mail as "Not spam" so it lands in your inbox next time.