nodejs/node

setTimeout Calling Callback Too Early

Open

#26 578 ouverte le 11 mars 2019

Voir sur GitHub
 (36 commentaires) (7 réactions) (0 assignés)JavaScript (35 535 forks)batch import
help wantedstaletimers

Métriques du dépôt

Stars
 (117 218 stars)
Métriques de merge PR
 (Merge moyen 18j 17h) (219 PRs mergées en 30 j)

Description

  • 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.

Guide contributeur