Citizen.Wait
What is Citizen.Wait?
Citizen.Wait
is a function that allows you to pause the execution of the current thread for a specified amount of time. This can be useful for creating delays, scheduling tasks, or controlling the flow of your script.
Under the hood Citizen.Wait
uses Lua coroutines, this means that they cannot be called outside of the scope of a coroutine (like CreateThread).
Syntax
Citizen.Wait(int milliseconds)
Note: You can also use Wait
alias to simplify your code and save some typing.
Required Arguments
- milliseconds: The amount of milliseconds to pause the current thread. This value determines how long the script will wait before continuing execution.
Examples
Basic Delay
CreateThread(function()
print("Starting delay...")
Wait(2000) -- Wait for 2000 milliseconds (2 seconds)
print("2 seconds have passed!")
end)
In this example, the script prints a message, waits for 2 seconds, and then prints another message.
Using Citizen.Wait in a Loop
CreateThread(function()
while true do
print("This message will print every 5 seconds.")
Wait(5000) -- Wait for 5000 milliseconds (5 seconds)
end
end)
In this example, the script will continuously print a message every 5 seconds.
while true do
loop without a Wait
will crash the clients game, please make sure your logic doesn’t accidentally prevent Wait
from being called.
CreateThread(function()
-- define how long we want to sleep for, by default we want to run per-frame
local sleep = 0
while true do
-- check if `E` was just pressed
if IsJustControlPressed(0, 38) then
-- we don't want to update for another second
sleep = 1000
if IsPedRunning(PlayerPedId()) then
print("Player is running!")
end
end
Wait(sleep) -- wait for however long `sleep` is defined as.
end
end)
This allow you to change the Wait
time to avoid having to always check when not necessary.
Things to keep in mind
Wait(0)
will pause the current coroutine until the next game tick.
Wait(2000)
will pause the current coroutine for approximately 2000 ms (2 seconds).
If a player is running at 60 fps they will have a tick happen once every 16.6ms.
If a player is running at 180 fps they will have a tick happen once every 5.5ms.
Best Practices
- Something that needs to run per frame should use
Wait(0)
: If something is required to run on every frame, you should always useWait(0)
usingWait(5)
,Wait(10)
, etc will cause ticks to be missed on higher frame rates. - Avoid calling heavy natives per-tick: Don’t call expensive native calls like START_EXPENSIVE_SYNCHRONOUS_SHAPE_TEST_LOS_PROBE per-frame if it can be avoided.
- Cache frequently called natives: Certain natives like PLAYER_PED_ID and GET_PLAYER_PED change infrequently, you can cache these in another
CreateThread
that runs less often to save some native calling overhead.