HeartBeatConnection is not disconnecting

I have an issue where the HeartBeatConnection is not disconnecting and it is spam printing “Disconnecting” which means it already passed the line which should disconnect the connection but it never did, anyone have any idea why?

image

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoidrootpart = character:WaitForChild("HumanoidRootPart")
local currentCamera = workspace.CurrentCamera
local Camera1 = workspace:WaitForChild("Camera1")
local MainMenu = game.SoundService:WaitForChild("Main Menu")
local RunService = game:GetService("RunService")
local Surrender	= player.PlayerGui:WaitForChild("SurrenderGui").TextButton
local TextBox = player.PlayerGui:WaitForChild("RPName").TextBox
local ImageButton = player.PlayerGui:WaitForChild("RPName").ImageButton

_G.FinishedUniform = false
_G.SelectingColor = false
local HeartBeatConnection

function PlayerInGame(Ingame)
	if Ingame then
		Surrender.Visible = true
		TextBox.Visible = true
		ImageButton.Visible = true
		print("All on")
		currentCamera.CFrame = CFrame.new(humanoidrootpart.Position)
		currentCamera.CameraType = Enum.CameraType.Custom
	end
end

coroutine.resume(coroutine.create(function()
	function HeartBeat()
		if _G.SelectingColor ~= true and game.ReplicatedStorage.InGame.Value == false then
			currentCamera.CFrame = currentCamera.CFrame * CFrame.Angles(0,0.001,0)
		end	
		if _G.FinishedUniform and _G.ColorFinished then
			game.Lighting.FogEnd = 5500000
			PlayerInGame(game.ReplicatedStorage.InGame.Value)
			HeartBeatConnection:Disconnect()
			print("disconnecting")
		end
	end
end))

function PlayernotInGame()
	Surrender.Visible = false
	TextBox.Visible = false
	ImageButton.Visible = false
	HeartBeatConnection = RunService.Heartbeat:Connect(HeartBeat)
	currentCamera.CFrame = CFrame.new(Camera1.Position)
	currentCamera.CameraType = Enum.CameraType.Scriptable
end

game.ReplicatedStorage.InGame.Changed:Connect(function(InGame)
	if not InGame then
		MainMenu:Play()
		PlayernotInGame()
	end
end)

if game.ReplicatedStorage.InGame.Value == false then
	MainMenu:Play()
	PlayernotInGame()
	HeartBeatConnection = RunService.Heartbeat:Connect(HeartBeat)
end

Over here, in the first line, when you run the PlayernotInGame function, it’s creating a new connection, and before you even have a chance to disconnect it, you run the second line, which creates a second connection. So even if the variable HeartBeatConnection only points to the second connection. So even if you disconnect the second connection, the first connection would keep running while trying to disconnect the second connection (which was already disconnected). Hope this helps!

I have put print here to check if the function was called before the connection happens but it only printed once so there suppose to be only one connection?