Best asynchronous loop?

What’s the best method to make a never-ending loop asynchronously?

I have seen many methods, which one is the best?

task.spawn(function()
    while true do
-- do something ...
    end
end)
	coroutine.resume(coroutine.create(function()
		while task.wait() do
-- do somthing ...
	end))
1 Like

I’d say something like

game:GetService("RunService"):Connect(function(delta)
    -- do something...
end)

but if you need to be able to eventually break out of the loop I would do something like

coroutine.wrap(function()
    while true do
        -- do something...
        task.wait()
    end
end)()

or task.spawn(), I think there is a difference but I don’t really remember.

1 Like

I think coroutine is more flexible, while task.spawn() its easier to use at least for me.
The RunService step its great too cause fires faster and it has different moments when it fires, like before rendering, before physics, after etc, and it actually has a stop, just connecting the RunService step, store it into a variable, then use the variable to disconnect it RSconnection:Disconnect()

2 Likes

Nice, yeah i was wanting to make a loop inside of OnPlayerAdded.

I think the final purpose of whats gonna do the loop is what aims to the better approach, which loop is better depends on the task

2 Likes

Just a while true loop that fires every second checking client to server latency.

Honestly I never created a latency reader system before, maybe someone could throw some light into this topic. I would do it by using the RunService step, kinda makes sense to me.

Oh but I forgot, it should be 1 per second, that would require reading delta time inside the RunService.
So… idk which one would be better for that task xD

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.