githubEdit

Use Coroutines

Run sequenced operations over time without blocking

Learn how to use coroutines to run code over multiple frames, create delays, and sequence operations. Coroutines in Needle Engine are built on JavaScript generators and run on the main thread, pausing and resuming execution across frames without blocking.

:::tip Related Guide If you're new to Needle Engine components, start with Use Lifecycle Hooksarrow-up-right to learn about awake(), start(), and update() methods. Coroutines are a complementary tool for time-based and sequenced operations. :::

:::tip When to Use Coroutines

  • Sequence operations with delays between them

  • Animate values over time

  • Wait for conditions to be met

  • Run periodic tasks without update()

  • Load resources with delays or retries

  • Create smooth transitions and effects :::

:::warning When NOT to Use Coroutines For code that needs to run every frame (like continuous movement, rotation, or input handling), use the update() lifecycle method instead. See Lifecycle Hooksarrow-up-right for more details. :::


Quick Start

Basic component using a coroutine:

import { Behaviour, WaitForSeconds } from "@needle-tools/engine";

export class Spawner extends Behaviour {
    start() {
        // Start a coroutine
        this.startCoroutine(this.spawnRoutine());
    }

    *spawnRoutine() {
        while (true) {
            this.spawnEnemy();
            yield WaitForSeconds(2); // Wait 2 seconds
        }
    }

    private spawnEnemy() {
        console.log("Enemy spawned!");
    }
}

:::tip JavaScript Generators Coroutines use JavaScript generator functions (function*). The yield keyword pauses execution and resumes on the next frame or after a wait. Unlike web workers or threads, coroutines run on the main thread—they don't create true parallelism but allow you to write sequential code that executes over time. :::


Wait Methods

Needle Engine provides several wait methods for coroutines:

WaitForSeconds

Wait for a specific amount of time in seconds:

WaitForFrames

Wait for a specific number of frames:

yield null

Wait for the next frame:


Common Patterns

Timed Display Updates

Update UI or text at regular intervals:

Fade Effect

Smoothly animate values over time:

Delayed Sequence

Execute multiple actions with delays:

Wait for Condition

Wait until a condition is met:

Periodic Task

Run a task repeatedly with delays:


Stopping Coroutines

You can stop coroutines by storing the generator reference:

:::tip Automatic Cleanup Coroutines are automatically stopped when a component is disabled or destroyed, so you don't need to manually stop them in most cases. :::


Coroutines vs update()

When should you use coroutines instead of update()?

Use Coroutines when:

  • You need delays between operations

  • You're sequencing multiple steps

  • You want code to run periodically (not every frame)

  • You're waiting for conditions or events

  • You need clearer, more readable sequential logic

Use update() when:

  • You need to run code every frame

  • You're doing continuous animation or movement

  • You need maximum performance (less overhead)

  • You're implementing physics or game logic that updates constantly


Advanced: Nested Coroutines

You can yield other coroutines:


Best Practices

:::tip Do's

  • Use coroutines for time-based sequences

  • Stop coroutines when they're no longer needed

  • Use meaningful variable names for wait times

  • Check conditions before long operations

  • Use WaitForSeconds for time-based delays :::

:::warning Don'ts

  • Avoid infinite loops without yields (will freeze)

  • Don't use coroutines for every-frame updates

  • Don't forget to yield in loops

  • Avoid too many simultaneous coroutines (performance) :::


Next Steps


Last updated