Skip to main content
Version: Unreleased

createWorkletRuntime

createWorkletRuntime lets you create a new JS runtime which can be used to run worklet functions possibly on different threads than JS or UI thread. Use this function if you need to integrate with Worklet Runtimes in C++.

The return value represents the runtime. You can pass it to the C++ side using JSI (JavaScript Interface) for further operations.

Reference​

Usage in JavaScript​

The initializer runs in the new runtime on the creating thread, before createWorkletRuntime returns. It sets a global variable that the scheduled task later reads on the worker's own thread. Compare the thread IDs in the console: the initializer and creator match, while the scheduled task has a different ID.

Code

Code

Colours connect each executing thread to its current code line. Recently executed lines fade over the next three ticks.

function initialize() {
'worklet';
(globalThis.message = 'Ready');
console.log('Initializer thread:', getCurrentThreadId());
}
function runTask() {
'worklet';
console.log(globalThis.message); // Ready
console.log('Worker thread:', getCurrentThreadId());
}
const worker = createWorkletRuntime({
name: 'background',
initializer: initialize,
});
console.log('Creator thread:', getCurrentThreadId());
scheduleOnRuntime(worker, runTask);

Usage in C++​

#include <worklets/WorkletRuntime/WorkletRuntime.h>

void scheduleNativeWork(
facebook::jsi::Runtime &rnRuntime,
const facebook::jsi::Value &runtimeValue) {
auto worker = worklets::extractWorkletRuntime(rnRuntime, runtimeValue);

worker->schedule([](facebook::jsi::Runtime &workerRuntime) {
workerRuntime.global().setProperty(workerRuntime, "nativeWorkFinished", true);
});
}

rnRuntime owns the incoming runtimeValue. The scheduled callback receives the worker's JSI runtime and runs on its queue with the runtime lock held. Keep the default queue and locking enabled for this example, and retain the Worker Runtime while its work is pending.

Use worker->runSync(...) for a short synchronous operation on the calling thread.

Type definitions

type WorkletRuntime = {
__hostObjectWorkletRuntime: never;
readonly name: string;
readonly runtimeId: number;
};

type WorkletRuntimeConfig = {
name?: string;
initializer?: () => void;
animationQueuePollingRate?: number;
enableNetworking?: boolean;
abortable?: boolean;
queue?: 'default' | object | null;
} & (
| { enableEventLoop?: boolean; enableLocking?: true }
| { enableEventLoop?: false; enableLocking: false }
);

function createWorkletRuntime(
config?: WorkletRuntimeConfig
): WorkletRuntime;

Arguments​

config​

Runtime configuration object.

name​

A name of the runtime used in debugging. Defaults to 'anonymous'.

initializer​

An optional worklet function that will be run synchronously on the same thread immediately after the runtime is created. It can be used to inject some global variables or functions into the runtime.

animationQueuePollingRate​

Time interval in milliseconds between polling of frame callbacks scheduled by requestAnimationFrame. Defaults to 16.

enableEventLoop​

Determines whether to enable the default event loop. Defaults to true. Always disabled on runtimes with enableLocking: false. When enabled, the runtime provides setTimeout, setImmediate, setInterval, requestAnimationFrame, queueMicrotask, clearTimeout, clearInterval, clearImmediate, and cancelAnimationFrame.

enableNetworking​
Available from 0.13.0

Determines whether the networking API - fetch, XMLHttpRequest and their supporting globals - is installed on the Runtime. Defaults to true.

abortable​
Available from 0.14.0

Determines whether the Runtime can be stopped with abortWorkletRuntime. With a custom queue, the Runtime's pending jobs are dropped only if the queue implements AsyncQueue::stop. Defaults to false.

enableLocking​
Available from 0.12.0

Determines whether access to the underlying JS runtime is synchronized with a mutex around every JSI operation. If not specified, it defaults to true. Can be disabled only together with the Event Loop.

Runtime without locking doesn't receive HMR updates and new Custom Serializable registrations.

Disable only when you can guarantee thread safety of all access to the runtime.

queue​

Controls the queue used for scheduling worklet functions on this runtime. Defaults to 'default'.

  • 'default': use the built-in queue implementation.
  • An object implementing the C++ AsyncQueue interface from <worklets/RunLoop/AsyncQueue.h>: use the provided custom queue.
  • null: do not attach any queue to the Runtime. Keep in mind that this will effectively disable all asynchronous features like Promises, setTimeout etc. Use it if you're going to implement the event-loop for the Runtime yourself.

Returns​

createWorkletRuntime returns a JavaScript object backed by a C++ worklets::WorkletRuntime, which derives from jsi::HostObject.

Remarks​

  • Worklet runtimes come with performance.now and console.* methods installed out-of-the-box. Other APIs are not available and need to be injected into the runtime or captured via worklet closure.

  • In development mode, all unhandled errors thrown in the runtime (except for those thrown in initializer) will be caught and thus logged to the console and displayed in a LogBox.

Platform compatibility​

NativeWeb
✅❌