Fix Bun.sleepSync to actually use milliseconds (#2242)

* Fix Bun.sleep/sleepSync to actually use milliseconds

`Bun.sleepSync` was accidentally treating its argument as seconds rather than milliseconds as the docs stated.  This is a breaking change in that the function now behaves as documented.  Fixed relevant tests.

* sleepSync: add more argument checking, tests
This commit is contained in:
Justin Whear
2023-03-02 09:00:20 -08:00
committed by GitHub
parent efdf647460
commit 20930849ce
3 changed files with 57 additions and 5 deletions

View File

@@ -861,12 +861,32 @@ pub fn sleepSync(
arguments: []const js.JSValueRef,
_: js.ExceptionRef,
) js.JSValueRef {
if (js.JSValueIsNumber(ctx, arguments[0])) {
const seconds = JSValue.fromRef(arguments[0]).asNumber();
if (seconds > 0 and std.math.isFinite(seconds)) std.time.sleep(@floatToInt(u64, seconds * 1000) * std.time.ns_per_ms);
// This function always returns undefined
const ret = js.JSValueMakeUndefined(ctx);
// Expect at least one argument. We allow more than one but ignore them; this
// is useful for supporting things like `[1, 2].map(sleepSync)`
if (arguments.len < 1) {
ctx.throwInvalidArguments("expected one argument, got {}", .{arguments.len});
return ret;
}
const arg = JSValue.fromRef(arguments[0]);
// The argument must be a number
if (!arg.isNumber()) {
ctx.throwInvalidArguments("argument to sleepSync must be a number, got {}", .{arg.jsTypeLoose()});
return ret;
}
return js.JSValueMakeUndefined(ctx);
//NOTE: if argument is > max(i32) then it will be truncated
const milliseconds = arg.coerce(i32, ctx);
if (milliseconds < 0) {
ctx.throwInvalidArguments("argument to sleepSync must not be negative, got {}", .{milliseconds});
return ret;
}
std.time.sleep(@intCast(u64, milliseconds) * std.time.ns_per_ms);
return ret;
}
pub fn createNodeFS(

View File

@@ -1,4 +1,4 @@
const interval = 0.01;
const interval = 10;
const now = performance.now();
console.time("Slept");
Bun.sleepSync(interval);

View File

@@ -0,0 +1,32 @@
import { it, expect } from "bun:test";
import { sleepSync } from "bun";
it("sleepSync uses milliseconds", async () => {
const start = Date.now();
sleepSync(5);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(5);
expect(end - start).toBeLessThan(10);
});
it("sleepSync with no arguments throws", async () => {
expect(() => sleepSync()).toThrow();
});
it("sleepSync with non-numbers throws", async () => {
expect(() => sleepSync(true)).toThrow();
expect(() => sleepSync(false)).toThrow();
expect(() => sleepSync("hi")).toThrow();
expect(() => sleepSync({})).toThrow();
expect(() => sleepSync([])).toThrow();
expect(() => sleepSync(undefined)).toThrow();
expect(() => sleepSync(null)).toThrow();
});
it("sleepSync with negative number throws", async () => {
expect(() => sleepSync(-10)).toThrow();
});
it("can map with sleepSync", async () => {
[1, 2, 3].map(sleepSync);
});