Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can someone provide me an explanation between coroutines, spawn(), and delay()?

Coroutines and spawns seem to do the exact same thing, although coroutines can be suspended or resumed, but what exactly is the major difference and uses between these things?

1 comment

1

spawn() run a function after a small and arbitrary delay (around the time the wait() yield), so yes kinda exactly the same, while delay() will run a function after the set amount of time without yielding the thread so basically delay is coroutine.resume(coroutine.create(function() wait(time) foo() end))

1 answer

✓ Accepted answer

The simplest explanation:

All of the functions mentioned above correlate to a universal programming topic known as Threading. A program runs synchronously, meaning each process is executed linearly. All of these processes fall under something known as the main thread. At times a certain instruction, or scope of instructions, can yield this main thread causing the rest of the following processes to queue.

Sometimes, we wish for the program's execution to continue while we're executing another instruction set; we wish to prevent this yield from occurring. To achieve this, we place these processes onto separate threads, enabling asynchronous action.


One way to allow this is by simply spawning our processes on a new thread—see the hyperlink in "Threading" to learn more about the spawn function. With this, the function will begin executing immediately. This is good for some quick looping.

When it comes to Coroutines (Co-routines), we can gain more control over how this is done.

1). You can enable the function to always run on a separate thread via the .create() function when called upon.

2). You can control the threads progression, through .yield() & .resume() (these are self-explanitory).


When it comes to delay(float DelayTime, function Callback), this function will allow you to prepare a process to run on a separate thread after a specified amount of time has elapsed.

Keep in mind, there are details and conditions left out of this to avoid complexity, I highly advise you to read up on the documentation to get a full debrief.

This discussion is preserved as it was. New answers, comments, and votes are closed.