Skip to content

setTimeout Calling Callback Too Early #26578

Open

Description

@fishcharlie
  • Version: v8.15.1
  • Platform: Darwin Charlies-MacBook-Pro.local 18.2.0 Darwin Kernel Version 18.2.0: Thu Dec 20 20:46:53 PST 2018; root:xnu-4903.241.1~1/RELEASE_X86_64 x86_64

I have the following code in Node.js.

const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

I'm trying to test this code with the following test:

it("Should wait for given time before resolving", async () => {
    const MS = 100;
    const start = process.hrtime();

    await timeout(MS);

    const diff = process.hrtime(start);
    expect(((diff[0] * NS_PER_SEC) + diff[1]) / 1000000).to.at.least(MS);
});

The problem is sometimes (rarely), this test fails:

Should wait for given time before resolving:

  AssertionError: expected 99.595337 to be at least 100
  + expected - actual

  -99.595337
  +100

Obviously this is some type of timing issue with Node.js or something. If anything I expect await timeout(MS); to take slightly longer than MS. In no case do I expect it to take less time.

What is it about the internals of JavaScript/Node.js that causes this to happen?

This occurred on macOS 10.14.3 running Node.js version 8.15.1.

Activity

  1. added
    timers
    on Mar 11, 2019
  2. devsnek commented on Mar 11, 2019

    @devsnek
    Member

    @bnoordhuis iirc there was another issue about timeouts firing early but i can't find it

  3. ZYSzys commented on Mar 11, 2019

    @ZYSzys
    Member

    @devsnek I think you were saying #26155 if I'm not wrong.

  4. Trott commented on Mar 11, 2019

    @Trott
    Member

    /ping @nodejs/timers

    I'm able to replicate using Node.js 8.15.1, 10.15.3, and 11.11.0. Here's the code I used. Start it and let it run for maybe 20 seconds or so and it will produce the error.

    'use strict';
    const assert = require('assert');
    
    const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    
    const test = async () => {
        const MS = 100;
        const start = process.hrtime();
    
        await timeout(MS);
    
        const diff = process.hrtime(start);
        const actual = ((diff[0] * 1e9) + diff[1]) / 1000000;
        assert(actual > MS, `${actual} ${MS}`);
        console.log('cool', actual, MS);
        setImmediate(test);
    };
    
    test();

    OS info:

    $ uname -a
    Darwin Fhqwhgads.local 17.7.0 Darwin Kernel Version 17.7.0: Thu Dec 20 21:47:19 PST 2018; root:xnu-4570.71.22~1/RELEASE_X86_64 x86_64
    $ 
  5. added
    confirmed-bug
    on Mar 11, 2019
  6. lpinca commented on Mar 11, 2019

    @lpinca
    Member

    Can reproduce with the above test case.

    $ uname -a
    Darwin imac 18.2.0 Darwin Kernel Version 18.2.0: Thu Dec 20 20:46:53 PST 2018; root:xnu-4903.241.1~1/RELEASE_X86_64 x86_64
    
  7. Trott commented on Mar 11, 2019

    @Trott
    Member

    I'd be interested to know if non-macOS users are seeing this or not.

  8. targos commented on Mar 11, 2019

    @targos
    Member

    I can reproduce on Windows:

    PS C:\Users\targo\Desktop> node test
    cool 103.681201 100
    cool 100.133799 100
    cool 101.023601 100
    cool 100.028599 100
    cool 100.9503 100
    cool 100.593501 100
    cool 100.9425 100
    cool 100.4715 100
    (node:6896) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: 99.9421 100
        at Immediate.test (C:\Users\targo\Desktop\test.js:14:5)
    
  9. added
    confirmed-bug
    and removed
    confirmed-bug
    on Mar 11, 2019
  10. Fishrock123 commented on Mar 11, 2019

    @Fishrock123
    Contributor

    fwiw:

    libuv loop times only run with millisecond precision:

    The comes from the fact that libuv only tacks loop times to millisecond precision: https://github.com/libuv/libuv/blob/2d2af382ce84b91d6ee7a185af32fca7f0acd84b/src/unix/internal.h#L289-L293

    I do think that should round correctly though?

    Measuring this "correctly" shows no issue though:

    'use strict'
    const assert = require('assert')
    const { internalBinding } = require('internal/test/binding')
    const { getLibuvNow } = internalBinding('timers')
    const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
    
    const test = async () => {
        const MS = 100
        const start = getLibuvNow()
    
        await timeout(MS);
    
        const diff = getLibuvNow() - start
        assert(diff >= MS, `${diff} ${MS}`)
        console.log('cool', diff, MS)
        setImmediate(test)
    }
    
    test()
  11. lpinca commented on Mar 11, 2019

    @lpinca
    Member

    This is reproducible even with Date.now() so I guess Date.now() and uv_now() work differently.

  12. Fishrock123 commented on Mar 11, 2019

    @Fishrock123
    Contributor

    Correct, uv_now() is, last I recall, more 'stable' than Date.now().

  13. bnoordhuis commented on Mar 12, 2019

    @bnoordhuis
    Member

    I'm reasonably sure this is caused by the interaction between setImmediate() and setTimeout() because just setTimeout() doesn't reproduce it. To wit, this fails after some time:

    function test() {
      const start = process.hrtime.bigint()
      setTimeout(next, 100)
      function next() {
        const now = process.hrtime.bigint()
        const delta = now - start
        console.log(Number(delta / BigInt(1e6)),
                    Number(delta % BigInt(1e6)))
        if (delta < BigInt(100 * 1e6)) throw 'fail'
        setImmediate(test)
      }
    }
    test()

    Whereas this keeps on running:

    function test() {
      const start = process.hrtime.bigint()
      setTimeout(next, 100)
      function next() {
        const now = process.hrtime.bigint()
        const delta = now - start
        console.log(Number(delta / BigInt(1e6)),
                    Number(delta % BigInt(1e6)))
        if (delta < BigInt(100 * 1e6)) throw 'fail'
        test() // no setImmediate()
      }
    }
    test()

    My guess is that something somewhere does or doesn't call uv_update_time(), causing a slight discrepancy in the time base used for different timers.

  14. apapirovski commented on Mar 17, 2019

    @apapirovski
    Contributor

    As @Fishrock123 pointed out, this is kind of expected due to the rounding hence it usually being off by sub 1ms. It also makes sense that it only occurs when there's other process activity.

    Think about it like this:

    1. You schedule a timer for 50ms at 100.2ms which is equivalent to 100ms.
    2. If you don't have any other code running, libuv will let the system poll for 100ms which will be exact.
    3. You run the callback roughly at 150.2ms which is exactly 50ms later.

    Now imagine you introduce other code in there:

    1. You schedule a timer for 50ms at 100.2ms which is equivalent to 100ms.
    2. You schedule another timer for 48ms at 101ms.
    3. You poll for for 48ms.
    4. You come back to your second timer at 149ms and run its callback which, say, takes exactly 1ms.
    5. At 150ms, both libuv and node are under the impression that your timer is ready to fire even though it's still technically 0.2ms off.

    There's no real solution here other than making timers use more precise units under the hood.

  15. 32 remaining items

  16. Trott commented on Oct 21, 2023

    @Trott
    Member

    It is possible that this bug was fixed and was reintroduced again.

    Timers have always run with millisecond precision, so no, that's not really plausible.

    What is plausible, though, is that the underlying operation of Node.js was sufficiently altered by that commit that some test-for-timer-precision code that used to fail will pass and/or some that used to pass will fail. But that's all about underlying and often-unpredictable (and sometimes OS-dependent) quirks, not about the millisecond precision not being there. For example, a code change that makes timers less efficient will, ironically, reduce the likelihood that the timer runs "early", thus making timers appear to be less buggy. But the issue is still there.

    I appreciate that you took the time to do a git bisect on this issue, though. I imagine that took a long time to run. But, IIUC, timers have always run with millisecond precision in Node.js so there's always been a rounding-from-999.9-to-1000 issue in certain code. (/ping @nodejs/timers for correction/verification)

  17. panfiva commented on Aug 7, 2025

    @panfiva

    In WSL:

    • 20-second timeout triggers after 17.527 seconds
    • 40-second timeout triggers after 35.042 seconds
    • 120-second timeout triggered after 110.096 seconds
    • 1800-second timeout triggered after 1660 seconds

    It appears the longer the timeout, the worse precision I get and the error accumulates. I noticed, however, that in prod (docker container on AWS EC2), the issue did not happen.

    Node: v24.4.1
    
    Ubuntu 24.04.2 LTS
    
    WSL version: 2.6.0.0
    Kernel version: 6.6.87.2-1
    WSLg version: 1.0.66
    MSRDC version: 1.2.6228
    Direct3D version: 1.611.1-81528511
    DXCore version: 10.0.26100.1-240331-1435.ge-release
    Windows version: 10.0.26100.4652
    
    import { setTimeout as nodeSetTimeout } from 'node:timers/promises'
    async function f() {
      const dt = new Date()
      await nodeSetTimeout(40 * 1000)
      console.log(dt.toISOString())
      const dt2 = new Date()
      const diff = (dt2.valueOf() - dt.valueOf()) / 1000
      console.log(dt2.toISOString())
      console.log(diff)
    }
    
    f()
  18. ebarzilay-godaddy commented on Aug 7, 2025

    @ebarzilay-godaddy

    For anyone running into these problems with WSL2 as in the above comment, or wondering how things could get so bad: it looks like WSL2 is a good test case that demonstrates the difference between Date.now() and performance.now(). Running the following simple loop:

    let d = Date.now();
    while (true) {
      const d2 = Date.now();
      if (d > d2) console.log(d - d2);
      d = d2;
    }

    in WSL2 shows a few seconds(!) adjustment every 30s, but this is not always happening. The huge adjustment also make look like it's not just some NTP syncs (even 70s casio watches were far from being so bad).

    My guess is that this is some timer syncing that responds to hypervisor priorities for the WSL2 VM. Running the same natively (on a linux, though I think that linux-vs-windows is a red herring) doesn't show any hiccups.

    Most people consider them roughly the same with different precision, but the huge difference in behavior in WSL2's VM vs a native run show that they're very different. I'd even go as far as saying that their respective results should be considered different types.

  19. added a commit that references this issue on Feb 18, 2026
  20. github-actions commented on Jun 27, 2026

    @github-actions
    Contributor

    This issue has been marked as stale due to 210 days of inactivity.
    It will be automatically closed in 30 days if no further activity occurs. If this is still relevant, please leave a comment or update it to keep it open.

  21. added
    stale
    on Jun 27, 2026
  22. SystemParadox commented on Jun 29, 2026

    @SystemParadox

    This is still the case with node 24.18.0 and 26.4.0.

  23. removed
    stale
    on Jun 30, 2026
  24. github-actions commented on Sep 29, 2026

    @github-actions
    Contributor

    This issue has been marked as stale due to 90 days of inactivity.
    It will be automatically closed in 30 days if no further activity occurs. If this is still relevant, please leave a comment or update it to keep it open.

  25. added
    stale
    on Sep 29, 2026
  26. SystemParadox commented on Sep 29, 2026

    @SystemParadox

    This is still relevant.

  27. removed
    stale
    on Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedtimers

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions