diff --git a/src/util.js.c b/src/util.js.c index cf9246c0..cd423159 100644 --- a/src/util.js.c +++ b/src/util.js.c @@ -194,13 +194,15 @@ bool tf_util_report_error(JSContext* context, JSValue value) } typedef struct _timeout_t { + uv_timer_t _timer; tf_task_t* _task; JSValue _callback; } timeout_t; static void _handle_closed(uv_handle_t* handle) { - tf_free(handle); + timeout_t* timeout = handle->data; + tf_free(timeout); } static void _util_timeoutCallback(uv_timer_t* handle) @@ -218,7 +220,6 @@ static void _util_timeoutCallback(uv_timer_t* handle) JS_FreeValue(context, result); JS_FreeValue(context, timeout->_callback); tf_trace_end(tf_task_get_trace(timeout->_task)); - tf_free(timeout); uv_close((uv_handle_t*)handle, _handle_closed); } @@ -231,16 +232,17 @@ static JSValue _util_setTimeout(JSContext* context, JSValueConst this_val, int a { ._task = task, ._callback = JS_DupValue(context, argv[0]), + ._timer = { .data = timeout }, }; - uv_timer_t* timer = tf_malloc(sizeof(uv_timer_t)); - memset(timer, 0, sizeof(uv_timer_t)); - uv_timer_init(tf_task_get_loop(task), timer); - timer->data = timeout; + uv_timer_init(tf_task_get_loop(task), &timeout->_timer); int64_t duration; JS_ToInt64(context, &duration, argv[1]); - uv_timer_start(timer, _util_timeoutCallback, duration, 0); + if (uv_timer_start(&timeout->_timer, _util_timeoutCallback, duration, 0) != 0) + { + tf_free(timeout); + } return JS_NULL; }