Pause a script, schedule work for later, and run two things at once — the clock behind every animation.
Games are full of timing: "open the door in 3 seconds", "shake the screen, then stop", "play the sound, then reset". The task library is the clock.
task.wait(seconds) pauses the script for that long:
print("Start")
task.wait(2)
print("Two seconds later")
The script freezes there for 2 seconds, then continues on the next line. You already met this in loops — it's the breath that keeps while true from freezing the game.
task.wait() with no argument waits one frame — about 1/60th of a second. You'll see it used to let the game catch up between heavy steps.
print('A'), then task.wait(3), then print('B') — how many seconds pass between printing A and printing B?
task.delay(seconds, function) doesn't pause anything. It schedules a function to run later, while the rest of the script keeps going:
print("Bomb armed")
task.delay(3, function()
print("Boom!")
end)
print("Back to business")
The order prints "Bomb armed", then "Back to business", then 3 seconds later "Boom!". The script didn't stop — it fired off a "call me in 3 seconds" note and moved on.
This is a sneak preview of a huge idea in Roblox: running things at the same time. task.delay starts one mini-program that runs later, while the main script continues.
task.spawn(function) starts a function immediately, but as a separate track:
task.spawn(function()
task.wait(2)
print("Side track done")
end)
print("Main track")
The main script prints "Main track" right away; the side track sleeps 2 seconds, then prints "Side track done". Both run at the same time — the main track doesn't wait for the side track.
An explosion happens 2 seconds after the fuse is lit, but the script must keep going. Write the scheduling line using task.delay and a function that prints 'BOOM'.
print("Fuse lit")
-- your scheduling here
Next: making your code readable with comments.