nodejs / nodejs/node

setTimeout Calling Callback Too Early

Offen
#26,578 36 Kommentare 7 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

help wanted timers
Vorherrschende Sprache
JavaScript
Sterne
122k
Forks
37.4k
Ø Merge
4 T. 3 Std.
Gemergte PRs (30 T.)
272

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem Timeout-Hilfsprogramm unter Verwendung von setTimeout und der Timing-Assertion unter Verwendung von process.hrtime. Vergleiche die beobachtete verstrichene Zeit mit der angeforderten Verzögerung und untersuche das im Issue beschriebene Verhalten der Node.js-Timer; die Arbeit ist abgeschlossen, wenn die Ursache erklärt oder eine reproduzierbare Korrektur und Validierung identifiziert wurde.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
javascript, nodejs
Bereich
backend
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Ruhig
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
38/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.