Threads and timers
Scripts must never block the game. Long-running work happens in threads: functions that pause with Wait and continue on a later tick.
CreateThread(function() while true do Wait(1000) -- pause one second; the game keeps running print('tick') endend)CreateThread(fn)startsfnon the next tick.Wait(ms)pauses the current thread.Wait(0)waits until the next tick.SetTimeout(ms, fn)runsfnonce after a delay.- Event handlers run as threads too, so they may call
Wait.
Always call Wait in loops
Section titled “Always call Wait in loops”Every time a thread runs, it gets a budget of instructions (50 million by default). A loop without Wait runs out of budget and the runtime stops that run with an error. Other resources keep running.
-- Wrong: never yieldsCreateThread(function() while true do endend)
-- RightCreateThread(function() while true do Wait(0) endend)Wait outside a thread
Section titled “Wait outside a thread”Wait at the top level of a script fails: Wait can only be called inside a thread or event handler. Wrap the code in CreateThread.
Measuring time
Section titled “Measuring time”GetGameTimer() returns milliseconds since the runtime started:
local started = GetGameTimer()Wait(250)print(GetGameTimer() - started) -- about 250The FiveM names Citizen.CreateThread, Citizen.Wait and Citizen.SetTimeout work as well.