Stop timer coroutine and restart it

  1. What do you want to achieve?
    If the bleedout event is fired and a coroutine (the timer) is running, I want it to cancel and restart the timer. Because the timers overlap if you get downed within 45 seconds again.

  2. What is the issue?
    If you get downed within 45 seconds again, the timer will overlap and will show the timer of the currently running one and the new one.

Here’s the ServerScript:


local timer = nil

function Format(Int)
	return string.format("%02i", Int)
end

function convertToHMS(Seconds)
	local Minutes = (Seconds - Seconds%60)/60
	Seconds = Seconds - Minutes*60
	return Format(Minutes)..":"..Format(Seconds) 
end

bleedoutevent.OnServerEvent:Connect(function(player)
	local char = player.Character

	timer = coroutine.create(function()
		for i = 45, 0, -1 do
			player.PlayerGui:WaitForChild("HUD"):WaitForChild("Frame"):WaitForChild("DownedTimer").Text = convertToHMS(i)
			task.wait(1)
			
			if i == 0 and char.DownedValues.Downed.Value == true and char.DownedValues.Revived.Value == false then
				char.Humanoid.Health = 0
				--wait(2)
				--char.DownedValues.Revived = false
				--char.DownedValues.Downed = false
				--char.Health.Enabled = true
			end
		end
	end)
	coroutine.resume(timer)
end)

And a video for visualization:
You can see the timer overlap in the GIF

Consider making the effect client sided as you’ll be able to have a better control over the coroutines.

However, for this I can only recommend adding in listeners for when the effect stops/the character dies and using coroutine.close() to stop the function.

1 Like