Skip to content

Commit

Permalink
fix: make sure Bun.sleep(Date) doesn't resolve prematurely (#8950)
Browse files Browse the repository at this point in the history
* fix: make sure Bun.sleep(Date) doesn't return prematurely

Fixes #8834.

This makes Bun.sleep(new Date(x)) fulfill its promise only when
Date.now() >= x.

* resolve test now #8834 is fixed

11 ms is in fact the right limit.

---------

Co-authored-by: John-David Dalton <john.david.dalton@gmail.com>
  • Loading branch information
argosphil and jdalton authored Feb 17, 2024
1 parent 135de4d commit e2c92c6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/bun.js/bindings/BunObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,8 @@ JSC_DEFINE_HOST_FUNCTION(functionBunSleep,

if (millisecondsValue.inherits<JSC::DateInstance>()) {
auto now = MonotonicTime::now();
auto milliseconds = jsCast<JSC::DateInstance*>(millisecondsValue)->internalNumber() - now.approximateWallTime().secondsSinceEpoch().milliseconds();
millisecondsValue = JSC::jsNumber(milliseconds > 0 ? milliseconds : 0);
double milliseconds = jsCast<JSC::DateInstance*>(millisecondsValue)->internalNumber() - now.approximateWallTime().secondsSinceEpoch().milliseconds();
millisecondsValue = JSC::jsNumber(milliseconds > 0 ? std::ceil(milliseconds) : 0);
}

if (!millisecondsValue.isNumber()) {
Expand Down
12 changes: 9 additions & 3 deletions test/js/web/timers/setTimeout.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,15 @@ it("Bun.sleep works with a Date object", async () => {
var ten_ms = new Date();
ten_ms.setMilliseconds(ten_ms.getMilliseconds() + 12);
await Bun.sleep(ten_ms);
// TODO: Fix https://github.com/oven-sh/bun/issues/8834
// This should be .toBeGreaterThan(11), or maybe even 12
expect(performance.now() - now).toBeGreaterThan(10);
expect(performance.now() - now).toBeGreaterThan(11);
});

it("Bun.sleep(Date) fulfills after Date", async () => {
let ten_ms = new Date();
ten_ms.setMilliseconds(ten_ms.getMilliseconds() + 12);
await Bun.sleep(ten_ms);
let now = new Date();
expect(+now).toBeGreaterThanOrEqual(+ten_ms);
});

it("node.js timers/promises setTimeout propagates exceptions", async () => {
Expand Down

0 comments on commit e2c92c6

Please # to comment.