How to break countdown loop when minimum number of players is no longer reached

I am making a system for a game where a 40 second countdown begins after 4 players have joined the server, this works fine. However, I am attempting to make it so the countdown cancels if any players leave making the player count go below 4.

However, when a player leaves the server, so far it will trigger my function for waiting for the minimum players, but will not break the countdown loop no matter what I do, causing the game to start regardless.

I have tried adding a ServerToClient remote event where if the minimum player drops below 4 it will trigger and break the loop, however, this doesn’t work.

Here is the code on the server side:

local module = require(script.Parent.ModuleScript)
local breakcount = game:GetService("ReplicatedStorage").ServerToClient.BreakCountdown



module.RequiredPlayersSystem()

while task.wait(5) do
	if #game:GetService("Players"):GetPlayers() <= 3 then
		module.RequiredPlayersSystem()
		breakcount:FireAllClients()
		end
end


Here is the code on the Client-Side countdown loop:

function module.IntermissionCountdown()
	local breakcount = game:GetService("ReplicatedStorage").ServerToClient.BreakCountdown
	local breakLoop = false
	breakcount.OnClientEvent:Connect(function()
		breakLoop = true
	end)
	for i = 40,0,-1 do
		local textbox = script.Parent.Intermission
		textbox.Visible = true
		textbox.Text = 'Intermission: '..tostring(i)
		task.wait(1)
		
		if breakLoop == true then
			breakLoop = false
			break
		end
		end
	
end

Hey there!

I’d recommend adding a print statement inside of the OnClientEvent on the client. This allows us to ensure that the event is fired. If you haven’t already, I’d highly recommend getting used to using print statements to search for the error cause.

Let me know your output!

on the client side the countdown does stop but, you should handle a break countdown loop on the server too.

the breakcount event was not firing, but the required players system function was.
I reversed the order and it fixed it, for some reason… do you know why this is so I could avoid it in the future? I don’t know why the remote event wouldn’t fire if the function was placed in front of it.

What do you mean with placed in front of it?

Also, I’d suggest listening to the PlayerRemoving event instead of checking every 5 seconds.