Parallel Threads

Running background tasks concurrently with your main script

Use spawnThread to run a background task concurrently with your main script. The background task runs in its own JS thread. All setGlobalVar / getGlobalVar calls are thread-safe, making them the intended communication channel between threads.

spawnThread(fn)

Spawns a background thread that calls the given function once. To make it repeat, simply wrap its contents in a while(!isStopped()) loop. This gives you full control over whether a task runs once or continuously.

At most 64 spawned threads may be alive at once; further spawns are silently dropped. Each thread gets its own JS context, so local variables and closures do not cross over — but top-level function declarations from the main script are re-declared inside every spawned context, so helper functions stay callable. Note that region.highlight() consumes one of the 64 slots for its deferred clear.

ParameterTypeDescription
fnfunctionThe background task to execute

Returns void — returns immediately; the function runs in the background

// Background vision loop — updates a global var continuously
spawnThread(function() {
  while(!isStopped()) {
    var pos = findObject("enemy");
    setGlobalVar("enemy_x", pos ? pos.cx : -1);
    wait(100);
  }
});

// One-off background task — runs once then finishes
spawnThread(function() {
  print("Background task started...");
  wait(2000);
  print("Background task finished!");
});
Threading model: Each spawnThread call creates one separate JS context and thread. Calls within one spawnThread block are still sequential — to run two things truly in parallel, use two separate spawnThread calls.
Limitation — touch gestures: Android only allows one active gesture at a time. If multiple spawnThread threads each call longPress simultaneously, they will cancel each other, causing rapid flickering. Use multiLongPress instead when you need to hold several touch points at once.

isStopped()

Returns true when the macro has finished or the user has pressed Stop. Useful for conditional logic inside a spawnThread body when you need to break out early rather than waiting for the next loop iteration.

Returns boolean

// Mid-loop early exit when a condition is met
spawnThread(function() {
  while (!isStopped()) {
    if (findObject("game_over") !== null) return; // exit immediately
    var pos = findObject("target");
    setGlobalVar("tx", pos ? pos.cx : -1);
    wait(100);
  }
});

// Also usable in the main script
while (!isStopped()) {
  findAndTap("collect_btn");
  wait(500);
}
Note: Spawned threads must check isStopped() as their loop condition — they do not stop automatically when the main script ends. A thread that never checks will be forcibly interrupted after a short shutdown budget.