DEV Community

aguro_key
aguro_key

Posted on

Stop using wait() in Roblox: the task library explained (with a cancellable timeout)

Old Roblox tutorials still use wait(), spawn() and delay(). They work, but they run on the legacy scheduler and can throttle or drift. The task library is the current replacement.

The swap

-- old
wait(1)
spawn(function() print("hi") end)
delay(2, function() print("later") end)

-- current
task.wait(1)
task.spawn(function() print("hi") end)
task.delay(2, function() print("later") end)
Enter fullscreen mode Exit fullscreen mode

Why it matters

  • task.wait() resumes on the next engine step and returns the real time waited. Plain wait() can be throttled when the game is busy.
  • task.spawn runs the function immediately until it yields. spawn waits a frame first, which causes ordering bugs.
  • task.defer runs the function at the end of the current step. Use it when you want "after this code finishes, but this frame".
  • task.cancel(thread) stops a thread you started with task.delay or task.spawn. The old functions give you no way to do that.

A small pattern: cancellable timeout

local timeout = task.delay(5, function()
    warn("Request took too long")
end)

local ok, result = pcall(function()
    return MyRemoteFunction:InvokeServer()
end)

if ok then
    task.cancel(timeout)
end
Enter fullscreen mode Exit fullscreen mode

If the call returns in time, the warning never fires.

Quick rules

  1. Use task.wait in every loop. Never use a bare while true do end without a wait.
  2. Use task.spawn for work that should start now. Use task.defer when order matters.
  3. Keep the thread handle if you may need to cancel it.

Related

I keep a starter kit of safe, server-validated Roblox scripts (datastore, shop, leaderboard) here: Roblox Game Starter Kit. There is a launch code LAUNCH25 for 25% off until Dec 17. The tutorial above is free either way.

Top comments (0)