How do you start a coroutine over?

  1. What do you want to achieve? Keep it simple and clear!

A bindable event connects to a function where a coroutine that counts down from 5 starts. I wish to make it so that the countdown starts over from five every time the event triggers.

  1. What is the issue? Include screenshots / videos if possible!

Every time the bindable is called the coroutine starts without resuming. This means the first time, it will countdown properly, but if I trigger the event while the countdown is at 3, now there are two overlapping countdowns.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I tried yielding the coroutine and resuming it again, but to no avail. Does anyone happen to know the solution to my trouble?

game:GetService("ServerScriptService").Bindables.TestBindable.Event:Connect(function()
	local c = coroutine.create(function()
			print(5)
			task.wait(1)
			print(4)
			task.wait(1)
			print(3)
			task.wait(1)
			print(2)
			task.wait(1)
			print(1)
			task.wait(1)
			print(0)
	end)
	coroutine.resume(c)
end)

This might help.

Hello,

Instead of starting a new coroutine each time, store a reference to the existing coroutine and cancel it before starting a new one.

Try this

local TestBindable = game:GetService("ServerScriptService").Bindables.TestBindable
local countdownCoroutine

TestBindable.Event:Connect(function()
    -- If a countdown is already running, cancel it
    if countdownCoroutine then
        task.cancel(countdownCoroutine)
    end

    -- Create a new coroutine for the countdown
    countdownCoroutine = task.spawn(function()
        for i = 5, 0, -1 do
            print(i)
            task.wait(1)
        end
    end)
end)

1 Like

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