# Timers

### setTimeout

Executes a function once after a specified delay.

```lua
B2Lib.Timers.setTimeout(callback, delay, options)
```

**Parameters:**

* `callback` (function): Function to execute after delay
* `delay` (number): Delay in milliseconds
* `options` (table, optional): Timer options
  * `priority` (boolean): High priority execution (default: false)
  * `data` (any): Custom data attached to timer

**Returns:** string - Timer ID for management

**Example:**

```lua
local timerId = B2Lib.Timers.setTimeout(function()
    print("Executed after 5 seconds")
end, 5000)
```

### clearTimeout

Clears a timeout timer before it executes.

```lua
B2Lib.Timers.clearTimeout(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to clear

**Returns:** boolean - True if timer was cleared successfully

### setInterval

Executes a function repeatedly at specified intervals.

```lua
B2Lib.Timers.setInterval(callback, interval, options)
```

**Parameters:**

* `callback` (function): Function to execute repeatedly
* `interval` (number): Interval in milliseconds
* `options` (table, optional): Timer options
  * `maxExecutions` (number): Maximum number of executions
  * `priority` (boolean): High priority execution (default: false)
  * `data` (any): Custom data attached to timer

**Returns:** string - Timer ID for management

**Example:**

```lua
local timerId = B2Lib.Timers.setInterval(function()
    print("Executed every 2 seconds")
end, 2000, {maxExecutions = 10})
```

### clearInterval

Clears an interval timer to stop repeated execution.

```lua
B2Lib.Timers.clearInterval(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to clear

**Returns:** boolean - True if timer was cleared successfully

### countdown

Creates a countdown timer with tick callbacks and completion handling.

```lua
B2Lib.Timers.countdown(duration, onTick, onComplete, options)
```

**Parameters:**

* `duration` (number): Countdown duration in milliseconds
* `onTick` (function): Function called on each tick with remaining time
* `onComplete` (function): Function called when countdown completes
* `options` (table, optional): Countdown options
  * `tickInterval` (number): Tick interval in milliseconds (default: 1000)
  * `data` (any): Custom data attached to timer

**Returns:** string - Timer ID for management

**Example:**

```lua
local timerId = B2Lib.Timers.countdown(30000, function(remaining)
    print(math.ceil(remaining / 1000) .. " seconds left")
end, function()
    print("Time's up!")
end)
```

### stopwatch

Creates a stopwatch for precise timing with start, stop, pause, resume capabilities.

```lua
B2Lib.Timers.stopwatch(onTick, options)
```

**Parameters:**

* `onTick` (function, optional): Function called on each tick with elapsed time
* `options` (table, optional): Stopwatch options
  * `tickInterval` (number): Tick interval in milliseconds (default: 100)
  * `autoStart` (boolean): Auto-start the stopwatch (default: true)
  * `data` (any): Custom data attached to timer

**Returns:** table - Stopwatch object with control methods

* `start()`: Start the stopwatch
* `stop()`: Stop the stopwatch
* `pause()`: Pause the stopwatch
* `resume()`: Resume the stopwatch
* `reset()`: Reset the stopwatch
* `getElapsed()`: Get elapsed time in milliseconds

### debounce

Creates a debounced function that delays execution until after delay has passed since last call.

```lua
B2Lib.Timers.debounce(func, delay, options)
```

**Parameters:**

* `func` (function): Function to debounce
* `delay` (number): Delay in milliseconds
* `options` (table, optional): Debounce options
  * `immediate` (boolean): Execute on leading edge (default: false)
  * `maxWait` (number): Maximum wait time before execution

**Returns:** function - Debounced function

**Example:**

```lua
local debouncedSave = B2Lib.Timers.debounce(function(data)
    savePlayerData(data)
end, 1000)

-- Multiple rapid calls will only execute once after 1 second
debouncedSave(playerData)
```

### throttle

Creates a throttled function that executes at most once per delay period.

```lua
B2Lib.Timers.throttle(func, delay, options)
```

**Parameters:**

* `func` (function): Function to throttle
* `delay` (number): Throttle delay in milliseconds
* `options` (table, optional): Throttle options
  * `leading` (boolean): Execute on leading edge (default: true)
  * `trailing` (boolean): Execute on trailing edge (default: true)

**Returns:** function - Throttled function

### delay

Executes a function after a delay with arguments.

```lua
B2Lib.Timers.delay(func, delay, ...)
```

**Parameters:**

* `func` (function): Function to execute
* `delay` (number): Delay in milliseconds
* `...` (any): Arguments to pass to the function

**Returns:** string - Timer ID for management

### waitForCondition

Waits for a condition to become true with timeout support.

```lua
B2Lib.Timers.waitForCondition(condition, timeout, checkInterval)
```

**Parameters:**

* `condition` (function): Function that returns true when condition is met
* `timeout` (number, optional): Timeout in milliseconds (default: 10000)
* `checkInterval` (number, optional): Check interval in milliseconds (default: 100)

**Returns:** boolean - True if condition was met, false if timed out

**Example:**

```lua
local success = B2Lib.Timers.waitForCondition(function()
    return GetEntityHealth(PlayerPedId()) > 50
end, 5000, 200)
```

### waitForConditions

Waits for multiple conditions to become true.

```lua
B2Lib.Timers.waitForConditions(conditions, timeout, checkInterval)
```

**Parameters:**

* `conditions` (table): Array of condition functions
* `timeout` (number, optional): Timeout in milliseconds (default: 10000)
* `checkInterval` (number, optional): Check interval in milliseconds (default: 100)

**Returns:** table - Results for each condition

### pauseTimer

Pauses a timer, stopping its execution temporarily.

```lua
B2Lib.Timers.pauseTimer(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to pause

**Returns:** boolean - True if timer was paused successfully

### resumeTimer

Resumes a paused timer.

```lua
B2Lib.Timers.resumeTimer(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to resume

**Returns:** boolean - True if timer was resumed successfully

### clearTimer

Clears any type of timer.

```lua
B2Lib.Timers.clearTimer(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to clear

**Returns:** boolean - True if timer was cleared successfully

### clearAllTimers

Clears all timers or timers of a specific type.

```lua
B2Lib.Timers.clearAllTimers(type)
```

**Parameters:**

* `type` (string, optional): Timer type to clear ("timeout", "interval", "countdown", "stopwatch")

**Returns:** number - Number of timers cleared

### getTimerInfo

Gets detailed information about a specific timer.

```lua
B2Lib.Timers.getTimerInfo(timerId)
```

**Parameters:**

* `timerId` (string): Timer ID to get information for

**Returns:** table|nil - Timer information or nil if not found

* `id` (string): Timer ID
* `type` (string): Timer type
* `paused` (boolean): Whether timer is paused
* `priority` (boolean): Timer priority
* `age` (number): Timer age in milliseconds
* `delay` (number): Timer delay (for timeouts)
* `interval` (number): Timer interval (for intervals)
* `elapsed` (number): Elapsed time
* `remaining` (number): Remaining time
* `progress` (number): Progress percentage (0.0 to 1.0)
* `executionCount` (number): Number of executions (for intervals)
* `maxExecutions` (number): Maximum executions (for intervals)

### getAllTimers

Gets information about all active timers.

```lua
B2Lib.Timers.getAllTimers()
```

**Returns:** table - Array of timer information objects

### getTimersByType

Gets all timers of a specific type.

```lua
B2Lib.Timers.getTimersByType(type)
```

**Parameters:**

* `type` (string): Timer type to filter by

**Returns:** table - Array of timer information objects

### getStats

Gets comprehensive timer system statistics.

```lua
B2Lib.Timers.getStats()
```

**Returns:** table - Timer system statistics

* `totalTimers` (number): Total number of active timers
* `timeouts` (number): Number of timeout timers
* `intervals` (number): Number of interval timers
* `countdowns` (number): Number of countdown timers
* `stopwatches` (number): Number of stopwatches
* `pausedTimers` (number): Number of paused timers
* `priorityTimers` (number): Number of priority timers
* `totalExecutions` (number): Total timer executions
* `averageExecutionTime` (number): Average execution time
* `memoryUsage` (number): Estimated memory usage
* `oldestTimer` (number): Age of oldest timer
* `newestTimer` (number): Age of newest timer

### cleanup

Cleans up old timers that have been inactive for a specified time.

```lua
B2Lib.Timers.cleanup(maxAge)
```

**Parameters:**

* `maxAge` (number, optional): Maximum age in milliseconds (default: 1800000)

**Returns:** number - Number of timers cleaned up

### Configuration

Configure the timers module in `config.lua`:

```lua
Config.Timers = {
    defaultTimeout = 10000,         -- Default timeout in milliseconds
    maxTimers = 1000,              -- Maximum number of active timers
    cleanupInterval = 300000,       -- Cleanup interval in milliseconds
    enableStatistics = true,        -- Enable statistics tracking
    enableDebugMode = false,        -- Enable debug logging
    priorityMultiplier = 0.5,       -- Priority timer multiplier
    maxExecutionTime = 100,         -- Maximum execution time warning
    enableMemoryTracking = true,    -- Enable memory usage tracking
    autoCleanupEnabled = true,      -- Enable automatic cleanup
    defaultTickInterval = 100,      -- Default tick interval for stopwatches
    maxDebounceDelay = 60000,      -- Maximum debounce delay
    maxThrottleDelay = 10000       -- Maximum throttle delay
}
```

### Troubleshooting

#### Timer Not Executing

1. Check that timer ID is valid and timer hasn't been cleared
2. Verify callback function is valid and doesn't throw errors
3. Check if timer is paused
4. Ensure delay/interval values are reasonable

#### Performance Issues

1. Reduce number of active timers
2. Use appropriate timer types for the task
3. Enable automatic cleanup for old timers
4. Monitor execution times and optimize callbacks

#### Memory Problems

1. Clear timers when no longer needed
2. Use cleanup function to remove old timers
3. Monitor memory usage with getStats()
4. Avoid creating too many short-lived timers

#### Timing Accuracy Issues

1. Use appropriate tick intervals for precision requirements
2. Consider game frame rate impact on timing
3. Use priority timers for critical timing
4. Account for callback execution time in intervals

#### Debounce/Throttle Problems

1. Verify delay values are appropriate for use case
2. Check leading/trailing edge settings
3. Ensure functions are properly bound
4. Test with different call patterns to verify behavior
