By default, the game refreshes the screen every 16 ms. If the main thread encounters time-consuming tasks within this time window, frame updates will be delayed, leading to stuttering and a poor user experience. Therefore, you are advised to offload these tasks to a worker thread. This asynchronous approach significantly enhances the game's smoothness and overall performance.
Both the task execution and communication between the worker thread and the main thread are handled asynchronously:

Quick game worker threads and main thread differ from web workers. The following table provides a detailed comparison between them.
| Capability | Quick Game Worker Thread | Quick Game Main Thread | Web Worker |
|---|---|---|---|
| Rendering |
|
|
|
| JS(qg) API |
|
|
|
| Network I/O |
|
|
|
| JS runtime |
|
|
|
| Timer |
|
|
|
| JIT |
|
| - |
| Engine capabilities |
|
| - |
| Concurrency | Cannot exceed 1 | - | No limitation |
| Thread communication data transmission mode | Structured clone | - | Structured clone/Transferable object |
| Thread communication data transmission type | JS object type and basic types | - | JS object type and basic types |
workers/index.js
├── game.js
├── manifest.json
└── workers // Directory that stores the worker script. The directory supports JS files, such as the worker script and its required scripts, but does not support static files such as images and videos.
└── index.js {
"workers": {
"path": "workers", // Relative path of the worker script, which is mandatory.
}
}worker.terminate()
const worker = qg.createWorker('workers/index.js')
The worker thread does not support quick game APIs starting with qg.
// The main thread sends a message to the worker thread.
// worker is the object returned by the qg.createWorker API called by the main thread.
worker.postMessage({
msg: 'hello from main'
})
// The worker thread sends a message to the main thread.
// In the worker thread, worker is a global variable.
worker.postMessage({
msg: 'hello from worker'
})// The main thread receives the message sent by the worker thread.
// worker is the object returned by the qg.createWorker API called by the main thread.
worker.onMessage((message) => {
console.log(`received message from worker: ${message}`)
})
// The worker thread receives the message sent by the main thread.
// In the worker thread, worker is a global variable.
worker.onMessage((message) => {
console.log(`received message from main: ${message}`)
})