First time using coroutine (searching for mistakes)

Hi,
I made a timer script and it’s my first time using coroutine so I just want to know if I can improve or correct something

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunTimer = ReplicatedStorage:WaitForChild("RunTimer")
local GamePart = ReplicatedStorage:WaitForChild("GamePart")
local Timer = ReplicatedStorage:WaitForChild("Timer")

local runTimer = coroutine.create(function(seconds)
	local timerStopTime = time() + seconds
	while task.wait() do
		local timeNow = time()
		if timeNow < timerStopTime then
			Timer.Value = timerStopTime - timeNow
		else
			if Timer.StartNextGamePartAtZero.Value then
				GamePart.Value += 1
			end
			
			local seconds = coroutine.yield()
			timerStopTime = time() + seconds
		end
	end
end)

RunTimer.Event:Connect(function(seconds)
	coroutine.resume(runTimer, seconds)
end)

GamePart.Value = 1

edit: it works if someone ask

2 Likes

First off, great job using coroutine correctly, especially for your first time; But, there is one thing you should change; Change your while loop to this:

while true do
    task.wait()
    -- Code here.
end

The reason is this: Using wait as your true value generally means you’re relying on wait to be true, and not nil or false. In the instance (very rare) where it is false or nil, your loop will break.

Incapaz explains it a little more into detail here.

3 Likes