I am trying to make a stopwatch I made stop counting when a BoolValue is false, and continue counting when it’s true again, but the problem is, the startTime written in the code below still keeps counting.
local function FormatTime(seconds)
local minutes = math.floor(seconds / 60)
local remainingSeconds = seconds % 60
return string.format("%02d:%02d", minutes, remainingSeconds)
end
spawn(function()
local startTime = os.clock()
while true do
local currentTime = os.clock() - startTime
local formattedTime = FormatTime(currentTime)
StopwatchLabel.Text = formattedTime
wait(1)
end
end)
How do I make this actually pause when a BoolValue is false, and then continue the countdown after the BoolValue is back to true? Please keep in mind that, this is not the full code.
You can add a check then move the time to a new value
spawn(function()
local startTime = os.clock()
local currentTime = 0
local stoppedTime = 0
while true do
if boolvalue.Value == true then
currentTime = os.clock() - startTime + stoppedTime -- adds it back
stoppedTime = 0 -- refresh
local formattedTime = FormatTime(currentTime)
StopwatchLabel.Text = formattedTime
wait(1)
else -- stops time
stoppedTime += currentTime
startTime = os.clock() -- refresh start time
currentTime = 0
end
end
end)
Have a try of this, I’ve put the ‘bool value’ to pause the stopwatch in the player (this is in a local script on my end).
local function FormatTime(seconds)
local minutes = math.floor(seconds / 60)
local remainingSeconds = seconds % 60
return string.format("%02d:%02d", minutes, remainingSeconds)
end
local playerGui = game.Players.LocalPlayer:WaitForChild("PlayerGui")
local scrGui = playerGui:WaitForChild("ScreenGui")
local StopwatchLabel = scrGui.TextLabel
local currentStopwatchTime = 0
local pauseTimeBool = game.Players.LocalPlayer:SetAttribute("IsPaused", false)
task.spawn(function()
local prevClockTick = os.clock()
local curClockTick = os.clock()
while true do
pauseTimeBool = game.Players.LocalPlayer:GetAttribute("IsPaused")
if pauseTimeBool then
curClockTick = os.clock()
prevClockTick = curClockTick
task.wait(1)
continue
else
curClockTick = os.clock()
currentStopwatchTime += curClockTick - prevClockTick
prevClockTick = curClockTick
local formattedTime = FormatTime(currentStopwatchTime)
StopwatchLabel.Text = formattedTime
task.wait(1)
end
end
end)
To note, I’ve also made ‘StopwatchLabel’ an object on my end, feel free to remove that part, and change the location of the bool value etc. Instead of using the os.clock() to set our time, we’re using it to get a current and previous tick, then ADDING it to a stopwatchTime variable, which we pass in the FormatTime method.
Is the attribute pre-created or is it created on a server/local script? I believe attributes replicate to clients, so even if you created it on the server, it should still be working if you’re using it in a local script, it just won’t be updating the attribute on the server.