Search code examples
timewhile-loopluaroblox

Stopwatch in Roblox Lua using a while loop


I am making a Roblox game and I want it to have a stopwatch. The stopwatch works, but it counts very slowly for some reason. Here's my ScreenGui in StarterGui: ScreenGui stopwatch

Here's the code inside the LocalScript:

local timer = script.Parent.Timer
local tms = 00
local ts = 00
local tm = 00
local tt
local tts
local y = 0
local whichtower = game.Players.LocalPlayer:FindFirstChild("WhichTower")
while true do
    wait(0.01)
    if whichtower.Value == "" then
        tms = 00
        ts = 00
        tm = 00
        tts = 0
    else
        tms = tms + 1
        if tms == 100 then
            ts = ts + 1
            tms = 0
            tts = tts + 1
            if ts == 60 then
                tm = tm + 1
                ts = 0
            end
        end
        tt = tostring(tm)..":"..tostring(ts)..":"..tostring(tms)
        timer.Text = tt
        game.Players.LocalPlayer:FindFirstChild("Time").Value = tt
    end
end

Solution

  • I have figured it out using a different set of code. Roblox limits the wait parameters to a minimum of 0.3 seconds, so that is why my previous code was not working.

    If you are looking at this, use task.wait(time) instead.