A discussion on the delay function is really a discussion on thread scheduling. Let's look at an example to see how this works.
Let's say, for example, I need to create a part that only exists temporarily. It might show up after a player touches a part, but it will go away shortly thereafter.
local Trigger = workspace.Trigger
Trigger.Touched:Connect(function(part)
local NewPart = Instance.new("Part")
NewPart.Parent = workspace
wait(3)
NewPart:Destroy()
end)
This is all well and good, until I have to have more code running during the time that the function is waiting those 3 seconds to destroy the part. How do we achieve multiple threads running at once?
There are multiple methods. Probably the most common is the spawn function. In short, using spawn() allows you to run code side-by-side with other code in the same script (or as close to side-by-side as possible). Here's an example:
local Trigger = workspace.Trigger
Trigger.Touched:Connect(function(part)
spawn(function()
local NewPart = Instance.new("Part")
NewPart.Parent = workspace
wait(3)
NewPart:Destroy()
end)
part.Parent:BreakJoints()
end)
So what does this mean? It means that the entirety of the code, involving the creation and destruction of the part, will all occur while the script keeps reading. Thus, we won't have to wait 3 seconds before it will run part.Parent:BreakJoints(). This function can be crucial sometimes!
Of course, you can also utilize Debris to perform the same function, as well as some complex Coroutines, on which, I can't lie, I have no knowledge worth sharing!
Without using any of these methods, calling the wait(3) would yield the thread, which, like I said, would cause part.Parent:BreakJoints() to wait 3 seconds before executing. With these functions, though, both threads run close to simultaneously.
Now that you somewhat understand how thread scheduling works, you can understand the delay() function. It is effectively the same as spawn(), except it accepts a time argument, which can be helpful when you want to cause that specific function to wait before running, without yielding the thread.
I cannot lie, delay() and spawn() seem to have completely interchangeable uses. In fact, I always use spawn() if needed, rather than delay(). As you continue coding, however, you'll find more and more situations, in which you need different and more specific functions!
#Accept and upvote if this helped!
Resources
Coroutines (if you want to torture yourself)
2 comments
I don’t have time right now to type up an answer so here is the documentation on delay: https://developer.roblox.com/en-us/api-reference/lua-docs/Roblox-Globals
Accept and upvote if my answer helped