How to stop a heartbeat

So i was coding a door that opens when you touch a part and closes after 10 seconds, but i don’t know how to stop the heartbeat loop. Does anyone know how to fix this?

Here’s the code!

local RunService = game:GetService("RunService")

local door = script.Parent.Parent.Door
local label = door.SurfaceGui.TextLabel
local running = false

function startTimer(timeLeft)
	print("started")
	running = true
	door.CanCollide = false
	door.Transparency = 0.7
	RunService.Heartbeat:Connect(function(delta)
		timeLeft -= delta

		local minutes = math.floor(timeLeft / 60)
		local seconds = math.floor(timeLeft % 60)
		local hundreths = math.floor(timeLeft % 1 * 100)

		label.Text = string.format("%02i:%02i.%02i", minutes, seconds, hundreths)
		if label.Text <= "00:00.00" then
			label.Text = "00:10.00"
			door.CanCollide = true
			door.Transparency = 0
			running = false
			-- Here needs to stop the runservice LOOK HERE!!!
		end
	end)
end

script.Parent.Touched:Connect(function(hit)
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player and running == false then
		startTimer(10)
	end
end)

Using a :Disconnect function

local RunService = game:GetService("RunService")

local door = script.Parent.Parent.Door
local label = door.SurfaceGui.TextLabel
local running = false

function startTimer(timeLeft)
	print("started")
	running = true
	door.CanCollide = false
	door.Transparency = 0.7
	heartbeat = RunService.Heartbeat:Connect(function(delta)
		timeLeft -= delta

		local minutes = math.floor(timeLeft / 60)
		local seconds = math.floor(timeLeft % 60)
		local hundreths = math.floor(timeLeft % 1 * 100)

		label.Text = string.format("%02i:%02i.%02i", minutes, seconds, hundreths)
		if label.Text <= "00:00.00" then
			label.Text = "00:10.00"
			door.CanCollide = true
			door.Transparency = 0
			running = false
			heartbeat:Disconnect()
		end
	end)
end

script.Parent.Touched:Connect(function(hit)
	local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
	if player and running == false then
		startTimer(10)
	end
end)
1 Like

I tried this using “local heartbeat = …” does it make a difference from using
local and not using local when you make the heartbeat a variable?

There are none though i would consider using local

It’ll not work if you set local heartbeat it will throw an error attempt to index nil with Heartbeat
I don’t know exactly but you can try.

1 Like