Creating an Interruptable Timer

Is there a way to create a timer that can be interrupted between seconds? I have tried to look at the template for laser tag to get more information but I still cannot figure it out. I want to make it so that if win condition is achieved the round ends prematurely. The current code I have for the timer right now is this:

for i=duration, 1, -1 do
	workspace:SetAttribute("Clock", i)
	task.wait(1)
end

There is probably some way to use it without task.wait but I can’t really think of a way to do so. If you have any feedback, that would be greatly appreciated!

1 Like

Set a condition within the loop to break if the win condition is met:

for secondsLeft = ROUND_LENGTH, 1, -1 do
    if --[[Round over condition]] then
        break
    end

    -- ...
  
    task.wait(1)
end

You can additionally wrap the timer in a thread for external interruption with task.cancel

3 Likes

So here’s kind of a general idea that I might use, not necessarily the “best” way to do it, but I doubt anyone would have any issues with it.

local CurrentTimer = 0
local RoundTime = 600 -- in seconds.

local function RoundEnded()
    -- Then you can put any logic in here such as determining who won.
end

local function StartRound()
    if CurrentTimer ~= 0 then
        return -- There's a round in progress.
    end
    
    CurrentTimer = RoundTime
    while CurrentTimer > 0 do
        CurrentTimer -= 1
        task.wait(1)
    end
    RoundEnded()
end

local function EndRoundEarly()
    CurrentTimer = 0
end

This is a super basic idea, but it’ll work for generic use-cases and is easy to adapt because it’s dead simple.

Thank you both for your feedback! While I put one as the solution, I will use more of mix of both.

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