# Thread API

The thread API lets you run callbacks on a background timer, independent of the render loop. Use it for periodic monitoring, data collection, or any task that doesn't need to run every frame.

> All examples use `snake_case`. Every function is also accessible in `camelCase` and `PascalCase` — the engine accepts all three. Pick one and stay consistent in your scripts.

***

### thread.create

```lua
local id = thread.create(callback, interval_ms)
```

| Parameter     | Type     | Required | Description                                        |
| ------------- | -------- | -------- | -------------------------------------------------- |
| `callback`    | function | yes      | Function to call repeatedly                        |
| `interval_ms` | number   | no       | Interval in milliseconds. Default: 100. Minimum: 1 |

Returns a `thread_id` number used to control the thread later.

```lua
local my_thread = thread.create(function()
    print("tick")
end, 500)
```

***

### thread.stop

```lua
thread.stop(thread_id)
```

Stops a specific thread and releases its callback.

```lua
thread.stop(my_thread)
```

***

### thread.stop\_all

```lua
thread.stop_all()
```

Stops every running thread at once.

***

### thread.is\_running

```lua
local running = thread.is_running(thread_id)
```

Returns `true` if the thread is still active.

```lua
if thread.is_running(my_thread) then
    print("still running")
end
```

***

### thread.set\_interval

```lua
thread.set_interval(thread_id, new_interval_ms)
```

Changes the interval of a running thread without stopping it.

```lua
thread.set_interval(my_thread, 200)
```

***

### Examples

**Background health monitor — create once, runs forever:**

```lua
local health_thread = nil

function on_frame()
    if health_thread ~= nil then return end

    health_thread = thread.create(function()
        local players = entity.get_players()
        for _, p in ipairs(players) do
            print(p.name .. " hp: " .. p.health)
        end
    end, 1000)
end
```

**Multiple threads at different rates:**

```lua
local threads = {}

function on_frame()
    if #threads > 0 then return end

    -- fast cache refresh
    threads[1] = thread.create(function()
        print("cache update")
    end, 200)

    -- slow status log
    threads[2] = thread.create(function()
        print("status check")
    end, 5000)
end
```

**Toggle thread on/off with a key:**

```lua
local monitor = nil

function on_frame()
    if input.is_key_down(0x4D) then  -- M key
        if monitor == nil then
            monitor = thread.create(function()
                print("monitoring...")
            end, 1000)
        else
            thread.stop(monitor)
            monitor = nil
        end
    end
end
```

**Lifecycle — create, check, adjust, stop:**

```lua
local my_thread = thread.create(function()
    print("working")
end, 1000)

if thread.is_running(my_thread) then
    thread.set_interval(my_thread, 500)
end

thread.stop(my_thread)

-- or stop everything at once
thread.stop_all()
```

***

### Notes

* Never call `thread.create` unconditionally inside `on_frame` — it runs every frame and will spawn thousands of threads. Guard with a nil check.
* Use threads for monitoring and background work. Use `on_frame` for all rendering and real-time input.
* Threads share the Lua state and can read globals written by `on_frame`.

***

### API Reference

| Function                      | Returns | Description               |
| ----------------------------- | ------- | ------------------------- |
| `thread.create(fn, ms)`       | number  | Create thread, returns ID |
| `thread.stop(id)`             | —       | Stop specific thread      |
| `thread.stop_all()`           | —       | Stop all threads          |
| `thread.is_running(id)`       | boolean | Check if thread is active |
| `thread.set_interval(id, ms)` | —       | Change thread interval    |

***

### Interval Guidelines

| Interval    | Use Case           |
| ----------- | ------------------ |
| 100–200ms   | Frequent updates   |
| 500–1000ms  | Regular monitoring |
| 2000–5000ms | Periodic tasks     |
| 5000ms+     | Infrequent checks  |

Use `on_frame` for rendering and real-time input. Use threads for everything else.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://project-vector-1.gitbook.io/vector-lua-engine/api/thread-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
