Scripting’s UI rendering system and the vast majority of JavaScript execution run on the main thread by default. In normal usage, developers rarely need to manually switch threads.
However, some system APIs or internal operations may occasionally execute on a background thread. To ensure UI updates are always safe, and to support running heavy work without blocking the main thread, Scripting provides the global Thread API.
Thread is a global namespace and does not require imports.
Thread.isMainThread: booleanIndicates whether the current JavaScript execution context is running on the main thread.
Most of the time this value is true, but certain system callbacks or asynchronous operations may occur on background threads. When performing UI updates, this property can be used to confirm that the current thread is safe for UI operations.
Thread.runInMain(execute: () => void): voidExecutes the given function on the main thread.
Because JavaScript normally runs on the main thread, you usually do not need to call this method explicitly. It is mainly useful when:
This method does not return a value and does not switch back to the previous thread. It simply guarantees synchronous execution on the main thread.
Thread.runInBackground<T>(execute: () => T | Promise<T>): Promise<T>Runs the provided function on a background thread and returns its result as a Promise. Once the background task completes, the result is delivered back on the thread that initiated the call (typically the main thread).
This is ideal for:
The function may return either a value or a Promise.
Async example:
Many asynchronous I/O methods in Scripting already run on background threads automatically, so developers do not need to manually call runInBackground for them.
Example:
readAsString automatically performs file reading on a background thread, then returns the result back on the thread where the call was made (usually the main thread).
This means asynchronous I/O will not block the UI, even if you call them directly in your UI logic.
For example:
Synchronous methods always execute on the main thread and do not switch threads internally.
Therefore:
readAsString) for better performancerunInBackground only when you must perform blocking synchronous work or heavy computationrunInMain is rarely neededrunInBackground for CPU-heavy or blocking synchronous tasksrunInMain to safely update UIrunInBackground; switch back first