Client and server in depth · Lesson 3/4 · 9 min
Threads and Wait(): performance without dying
Badly written loops are the #1 cause of lag in FiveM. Learn to use Wait() properly.
On the client, a lot of code runs in loops (threads). If a loop never rests (Wait), it tanks your FPS. The trick is to Wait long when nothing's happening and short only when needed.
The FPS killer
-- ❌ BAD: runs 60+ times per second ALWAYS
CreateThread(function()
while true do
Wait(0) -- never a permanent Wait(0)!
local ped = PlayerPedId()
-- heavy checks every frame…
end
end)Kills performance
The healthy version
CreateThread(function()
while true do
local sleep = 1000 -- by default rest 1s
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
local dist = #(coords - Config.ZonaTienda)
if dist < 20.0 then
sleep = 0 -- only when you're close does it run per frame
-- draw marker, detect E key, etc.
end
Wait(sleep)
end
end)Dynamic Wait
Golden pattern: a sleep variable that starts high (500-1000ms) and only drops to 0 when the player is close/interacting. That way your resource uses ~0.01ms while idle.
Practice what you learned
0/3¿Por qué un CreateThread con while true do Wait(0) permanente mata el rendimiento?
Pista
Piensa en cuántas veces corre por segundo.
Completa el patrón de Wait dinámico: descansa por defecto y solo va por frame cuando el jugador está cerca.
CreateThread(function() while true do local sleep = local dist = #(GetEntityCoords(PlayerPedId()) - Config.ZonaTienda) if dist < 20.0 then sleep = end (sleep) endend)Pista
Empieza en 1000ms, baja a 0 cuando estás cerca, y al final Wait(sleep).
Arregla este bucle para que no mate los FPS: que descanse 1000ms y solo vaya a 0 cuando dist < 20.0.
Este código tiene un fallo:
CreateThread(function() while true do Wait(0) local dist = #(GetEntityCoords(PlayerPedId()) - Config.ZonaTienda) if dist < 20.0 then DrawMarker(--[[ ... ]]) end endend)Reescríbelo corregido:
Pista
Sustituye el Wait(0) fijo por una variable sleep dinámica.
Challenge: code it yourself
Convert a loop that always draws 3D text into one that only works when the player is within 15 meters.
Write it yourself in your editor (VS Code) and test it on your server. You learn here by doing it, not by copying.
See hint
Compute #(coords - target); if dist<15 sleep=0 and draw, otherwise sleep=1000.
Escribe aquí tu solución:
