How can I run a timer and wait for an event at the same time

I’m currently making a turn-based game and I’m wondering how I can wait for an event to be fired while counting down a timer before the player is forced to move. Here is the code piece that i am struggling with.

I want the timer to run at the same time as it is waiting for the event to be called, and if the timer hits 0 i want the repeat to end.

timer.Value = 5

game.ReplicatedStorage.Events.SendInfo:FireClient(v, amt, true)

repeat 
        wait(.1)
        timer.Value -= .1
						
	until
timer.Value == 0 or player, types, amount = game.ReplicatedStorage.Events.SendInfo.OnServerEvent:Wait()

I typically spawn a new thread which handles timeout for this problem:

timer.Value = 5
ReplicatedStorage.Events.SendInfo:FireClient(v, amt, true)

local eventThread
local timeoutThread = task.defer(function()
        while timer.Value >= 0 do
                task.wait(0.1)
                timer.Value -= 0.1
        end

        -- force player interaction
        eventThread:Disconnect()
end)
eventThread = ReplicatedStorage.Events.SendInfo.OnServerEvent:Connect(function(player, types, amount)
        -- handle user interaction
        -- ...

        task.cancel(timeoutThread)
end)

If your requirements were more loose and did not require updating the remaining time on a Value, then you could simplify this by using task.delay instead.

If you didn’t have to do validation on your RemoteEvents when they are fired, you can further simplify this by using RBXScriptSignal:Once over :Connect.

3 Likes

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