When would I have to use spawn()?

Hello, I know what spawn does I am pretty sure it delays the function inside of it I just do not know when I would need to do something like that.

1 Like

spawn isn’t recommended to use as it has a wait() before it runs the given function and depending on conditions could take longer than 1/30th of a second before running your function. Use coroutines as they’re practically the same except coroutines do not have that wait()

If you want more info as to why spawn is bad, Spawn is evil by evaera and this entire thread should be good enough

3 Likes

i agree with the person above

instead of

spawn(function()
    --code
end)

use

coroutine.wrap(function()
    --code
end)()

or

coroutine.resume(coroutine.create(function()
    --code
end))

if you want it to behave like an improved spawn, do this:

coroutine.wrap(function()
    game:GetService("RunService").Heartbeat:Wait()
    --code
end)()

yes, game:GetService("RunService").Heartbeat:Wait() is a better alternative to wait()

to answer your question, spawn like coroutine.wrap, creates a “seperate thread”, which can be helpful in situation such as these:

while true do
    -- code to loop forever
end

spawn(function()
    --code
end) -- if this function was not spawned or wrapped as a coroutine, this will never run