Assistance with Capturing Script

I have a script for the capture of Hills (Capture points), when the palyer enters a zone it will start a function for 15 seconds for capturing (Each second it checks if the player is still in the area).
Now wheen the palyer exits the Area very fast and enters again, it doesn’t only fire the same function again, but it will also continue the previous one.
Any way I could fix this? (It’s a server script btw.)

local function startColorLoop(oldColor, teamColor, player)
	local originalColor = oldColor
	local loopStartTime = tick()
	local Capturing = true
	local iterationCounter = 0

	while tick() - loopStartTime < 15 and Capturing do
		local Array = zone:getPlayers()
		if #Array <= 0 then
			Capturing = false
			CaptureRE:FireClient(player, false)
			print("Player Left Zone")
			break
		end

		for _, v in pairs(Array) do
			if v.Team.TeamColor ~= teamColor then
				Capturing = false
				print("Enemy detected")
				CaptureRE:FireClient(player, false)
				break
			end
		end

		if not Capturing then
			break
		end

		tm.Value = teamColor
		updatecolor()
		wait(0.5)
		tm.Value = originalColor
		updatecolor()
		wait(0.5)
		iterationCounter = iterationCounter + 1

		if iterationCounter == 2 then
			UpdateDataStore:Fire(player, flag, "Capturing")
			iterationCounter = 0
		end
	end

	if Capturing then
		tm.Value = teamColor
		updatecolor()
		UpdateDataStore:Fire(player, flag, "Captured")
	else
		tm.Value = originalColor
		updatecolor()
	end
end

zone.playerEntered:Connect(function(player)
	if tm.Value ~= player.TeamColor then
		CaptureRE:FireClient(player, true)
		task.spawn(startColorLoop, tm.Value, player.TeamColor, player)
	end
end)

zone.playerExited:Connect(function(player)
	CaptureRE:FireClient(player, false)
end)
1 Like