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

lua
-- ❌ 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

lua
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
Test

¿Por qué un CreateThread con while true do Wait(0) permanente mata el rendimiento?

Pista

Piensa en cuántas veces corre por segundo.

Rellena los huecos

Completa el patrón de Wait dinámico: descansa por defecto y solo va por frame cuando el jugador está cerca.

1CreateThread(function()
2 while true do
3 local sleep =
4 local dist = #(GetEntityCoords(PlayerPedId()) - Config.ZonaTienda)
5 if dist < 20.0 then
6 sleep =
7 end
8 (sleep)
9 end
10end)
Pista

Empieza en 1000ms, baja a 0 cuando estás cerca, y al final Wait(sleep).

Corrige el error

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:

1CreateThread(function()
2 while true do
3 Wait(0)
4 local dist = #(GetEntityCoords(PlayerPedId()) - Config.ZonaTienda)
5 if dist < 20.0 then
6 DrawMarker(--[[ ... ]])
7 end
8 end
9end)

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:

How was this lesson?