Skip to content

task

Library · task · server and client scripts

task runs functions later or in their own threads, and pauses the running thread. Scheduled threads belong to the calling script: the engine drops them if the script reloads or its entity is destroyed. Waits and delays count update ticks, so they end on the first tick at or after the time.

cancel

Function
cancel(thread: thread) -> ()

task.cancel stops a thread from task.delay, task.defer or task.spawn so it never resumes.

Example

-- Server script in a part: despawn in 30 seconds unless something touches it.
local despawn = task.delay(30, function()
    self:Destroy()
end)

self:On(Component.Collider.Touched, function()
    task.cancel(despawn)
end)

defer

Property
defer: <A..., R...>(f: thread | (A...) -> R..., A...) -> thread

task.defer runs a function at the end of this tick, after every Update, and returns its thread.

Example

-- Server script.
task.defer(print, "second")
print("first")

delay

Property
delay: <A..., R...>(seconds: number, f: thread | (A...) -> R..., A...) -> thread

task.delay runs a function after seconds, and returns its thread. seconds must be a finite non-negative number.

Example

-- Server script in a part: the part disappears after 2 seconds.
task.delay(2, function()
    self:Destroy()
end)

spawn

Property
spawn: <A..., R...>(f: thread | (A...) -> R..., A...) -> thread

task.spawn runs a function at once, until it waits or ends, and returns its thread. An error in the function logs a Task error warning and does not stop the caller.

Example

-- Server script in a part: blink while the rest of the script goes on.
task.spawn(function()
    while true do
        self.Visible = false
        task.wait(0.5)
        self.Visible = true
        task.wait(0.5)
    end
end)
print("blinking")

wait

Function
wait(seconds: number?) -> number

task.wait pauses the running thread for at least seconds, or one tick when seconds is left out, and returns the seconds that passed. seconds must be a finite non-negative number when given.

Effects

  • Update, PhysicsUpdate and World.System callbacks cannot wait; start the waiting code with task.spawn instead.
  • A script finishes loading at its first top-level wait, so declare Update and PhysicsUpdate before it; see Update.

Example

-- Server script in a part: a platform that moves up and down every 3 seconds.
local low = self.Position
if not low then
    return
end
local high = low + Vector3.new(0, 6, 0)

while true do
    task.wait(3)
    self.Position = high
    task.wait(3)
    self.Position = low
end