Skip to content

Commit

Permalink
feat: add os.sleepAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
QuiiBz committed Apr 25, 2024
1 parent cf7adc8 commit 756452e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
6 changes: 6 additions & 0 deletions doc/quickjs.texi
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,12 @@ write_fd]} or null in case of error.
@item sleep(delay_ms)
Sleep during @code{delay_ms} milliseconds.

@item sleepAsync(delay_ms)
Asynchronouse sleep during @code{delay_ms} milliseconds. Returns a promise. Example:
@example
await os.sleepAsync(500);
@end example

@item setTimeout(func, delay)
Call the function @code{func} after @code{delay} ms. Return a handle
to the timer.
Expand Down
33 changes: 33 additions & 0 deletions quickjs-libc.c
Original file line number Diff line number Diff line change
Expand Up @@ -2119,6 +2119,38 @@ static JSClassDef js_os_timer_class = {
.gc_mark = js_os_timer_mark,
};

/* return a promise */
static JSValue js_os_sleepAsync(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
JSRuntime *rt = JS_GetRuntime(ctx);
JSThreadState *ts = JS_GetRuntimeOpaque(rt);
int64_t delay;
JSOSTimer *th;
JSValue promise, resolving_funcs[2];

if (JS_ToInt64(ctx, &delay, argv[0]))
return JS_EXCEPTION;
promise = JS_NewPromiseCapability(ctx, resolving_funcs);
if (JS_IsException(promise))
return JS_EXCEPTION;

th = js_mallocz(ctx, sizeof(*th));
if (!th) {
JS_FreeValue(ctx, promise);
JS_FreeValue(ctx, resolving_funcs[0]);
JS_FreeValue(ctx, resolving_funcs[1]);
return JS_EXCEPTION;
}
th->has_object = FALSE;
th->timeout = js__hrtime_ms() + delay;
th->func = JS_DupValue(ctx, resolving_funcs[0]);
list_add_tail(&th->link, &ts->os_timers);
JS_FreeValue(ctx, resolving_funcs[0]);
JS_FreeValue(ctx, resolving_funcs[1]);
return promise;
}

static void call_handler(JSContext *ctx, JSValue func)
{
JSValue ret, func1;
Expand Down Expand Up @@ -3711,6 +3743,7 @@ static const JSCFunctionListEntry js_os_funcs[] = {
// per spec: both functions can cancel timeouts and intervals
JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ),
JS_CFUNC_DEF("clearInterval", 1, js_os_clearTimeout ),
JS_CFUNC_DEF("sleepAsync", 1, js_os_sleepAsync ),
JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ),
JS_CFUNC_DEF("getcwd", 0, js_os_getcwd ),
JS_CFUNC_DEF("chdir", 0, js_os_chdir ),
Expand Down

0 comments on commit 756452e

Please sign in to comment.