Millisecond Stopwatch Start/End Question

I am working on a Millisecond Stopwatch that is started randomly and ended after a maximum of 120 seconds (3 seconds in the code for testing), where the current time is printed (formatted minutes:seconds:milliseconds), and as players touch a brick, be able to grab the current time and store that in the player’s time completed dictionary. This logs how long it took the player, by millisecond, to complete a stage when it is started, at any time.

However, I am trying to get an accurate millisecond timer using RenderStepped, but I am having a hard time turning it off when I am done.

I have tried a Coroutine with yield, break statement, and a while statement (setting a bool value) to the max value to have it stop, but RenderStepped is still being triggered.

The code believe includes a 1 second wait time (For testing) and then yields the coroutine, only for the HeartBeat function to continue to activate each heartbeat.

local function Stopwatch()

	local total = 0
	local maxTime = 3 -- in seconds
	local timeRunning = 0
	
local currentStopwatch = coroutine.create(game:GetService('RunService').Heartbeat:Connect(function(dt)
	print(timeRunning)
	  if timeRunning >= maxTime then
		print("time running is too high!")
	  else
		total = total + dt
        timeRunning = timeRunning + 1
		local mins = math.floor((total/60)%60)
		local seconds = math.floor(total%100)%60
		local milliseconds = math.floor(total%1 * 100)
		
		print(("%02d:%02d:%02d"):format(mins, seconds, milliseconds))
        end
    end))
wait(1)
coroutine.yield(currentStopwatch)
end

Stopwatch()
1 Like

– Began
local startTick = tick()

–End
local endTick = tick()

local milliseconds = endTick - startTick

Keep in mind server tick() and client tick()'s are different but that shouldn’t effect this case.