Timers
The Timers module provides comprehensive timer functionality for FiveM resources with advanced scheduling, timing control, and performance optimization.
setTimeout
Executes a function once after a specified delay.
B2Lib.Timers.setTimeout(callback, delay, options)
Parameters:
callback
(function): Function to execute after delaydelay
(number): Delay in millisecondsoptions
(table, optional): Timer optionspriority
(boolean): High priority execution (default: false)data
(any): Custom data attached to timer
Returns: string - Timer ID for management
Example:
local timerId = B2Lib.Timers.setTimeout(function()
print("Executed after 5 seconds")
end, 5000)
clearTimeout
Clears a timeout timer before it executes.
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.
B2Lib.Timers.setInterval(callback, interval, options)
Parameters:
callback
(function): Function to execute repeatedlyinterval
(number): Interval in millisecondsoptions
(table, optional): Timer optionsmaxExecutions
(number): Maximum number of executionspriority
(boolean): High priority execution (default: false)data
(any): Custom data attached to timer
Returns: string - Timer ID for management
Example:
local timerId = B2Lib.Timers.setInterval(function()
print("Executed every 2 seconds")
end, 2000, {maxExecutions = 10})
clearInterval
Clears an interval timer to stop repeated execution.
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.
B2Lib.Timers.countdown(duration, onTick, onComplete, options)
Parameters:
duration
(number): Countdown duration in millisecondsonTick
(function): Function called on each tick with remaining timeonComplete
(function): Function called when countdown completesoptions
(table, optional): Countdown optionstickInterval
(number): Tick interval in milliseconds (default: 1000)data
(any): Custom data attached to timer
Returns: string - Timer ID for management
Example:
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.
B2Lib.Timers.stopwatch(onTick, options)
Parameters:
onTick
(function, optional): Function called on each tick with elapsed timeoptions
(table, optional): Stopwatch optionstickInterval
(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 stopwatchstop()
: Stop the stopwatchpause()
: Pause the stopwatchresume()
: Resume the stopwatchreset()
: Reset the stopwatchgetElapsed()
: Get elapsed time in milliseconds
debounce
Creates a debounced function that delays execution until after delay has passed since last call.
B2Lib.Timers.debounce(func, delay, options)
Parameters:
func
(function): Function to debouncedelay
(number): Delay in millisecondsoptions
(table, optional): Debounce optionsimmediate
(boolean): Execute on leading edge (default: false)maxWait
(number): Maximum wait time before execution
Returns: function - Debounced function
Example:
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.
B2Lib.Timers.throttle(func, delay, options)
Parameters:
func
(function): Function to throttledelay
(number): Throttle delay in millisecondsoptions
(table, optional): Throttle optionsleading
(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.
B2Lib.Timers.delay(func, delay, ...)
Parameters:
func
(function): Function to executedelay
(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.
B2Lib.Timers.waitForCondition(condition, timeout, checkInterval)
Parameters:
condition
(function): Function that returns true when condition is mettimeout
(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:
local success = B2Lib.Timers.waitForCondition(function()
return GetEntityHealth(PlayerPedId()) > 50
end, 5000, 200)
waitForConditions
Waits for multiple conditions to become true.
B2Lib.Timers.waitForConditions(conditions, timeout, checkInterval)
Parameters:
conditions
(table): Array of condition functionstimeout
(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.
B2Lib.Timers.pauseTimer(timerId)
Parameters:
timerId
(string): Timer ID to pause
Returns: boolean - True if timer was paused successfully
resumeTimer
Resumes a paused timer.
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.
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.
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.
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 IDtype
(string): Timer typepaused
(boolean): Whether timer is pausedpriority
(boolean): Timer priorityage
(number): Timer age in millisecondsdelay
(number): Timer delay (for timeouts)interval
(number): Timer interval (for intervals)elapsed
(number): Elapsed timeremaining
(number): Remaining timeprogress
(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.
B2Lib.Timers.getAllTimers()
Returns: table - Array of timer information objects
getTimersByType
Gets all timers of a specific type.
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.
B2Lib.Timers.getStats()
Returns: table - Timer system statistics
totalTimers
(number): Total number of active timerstimeouts
(number): Number of timeout timersintervals
(number): Number of interval timerscountdowns
(number): Number of countdown timersstopwatches
(number): Number of stopwatchespausedTimers
(number): Number of paused timerspriorityTimers
(number): Number of priority timerstotalExecutions
(number): Total timer executionsaverageExecutionTime
(number): Average execution timememoryUsage
(number): Estimated memory usageoldestTimer
(number): Age of oldest timernewestTimer
(number): Age of newest timer
cleanup
Cleans up old timers that have been inactive for a specified time.
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
:
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
Check that timer ID is valid and timer hasn't been cleared
Verify callback function is valid and doesn't throw errors
Check if timer is paused
Ensure delay/interval values are reasonable
Performance Issues
Reduce number of active timers
Use appropriate timer types for the task
Enable automatic cleanup for old timers
Monitor execution times and optimize callbacks
Memory Problems
Clear timers when no longer needed
Use cleanup function to remove old timers
Monitor memory usage with getStats()
Avoid creating too many short-lived timers
Timing Accuracy Issues
Use appropriate tick intervals for precision requirements
Consider game frame rate impact on timing
Use priority timers for critical timing
Account for callback execution time in intervals
Debounce/Throttle Problems
Verify delay values are appropriate for use case
Check leading/trailing edge settings
Ensure functions are properly bound
Test with different call patterns to verify behavior
Last updated