How do i stop heartbeat functions?

I, made a script where the player can attract coins after pressing a keybind but i want to be so that the attraction stops after a certain amount of time, how can i do this?
this is the script

function Magnetoid()
	for _,c in pairs(game.Workspace.Coins:GetChildren()) do
		if (c.Position - character.HumanoidRootPart.Position).Magnitude < 50 then
			c.CanCollide = false
			c.CFrame = c.CFrame:Lerp(character.HumanoidRootPart.CFrame , 0.325)

			if (c.Position - character.HumanoidRootPart.Position).Magnitude <= 1 then
				local tweenTransparency = tween_service:Create(c,
					TweenInfo.new(0.5,Enum.EasingStyle.Quad,
						Enum.EasingDirection.InOut
					),{
						Transparency = 1
					}
				)
				tweenTransparency:Play()
				tweenTransparency.Completed:Wait()
				game.Debris:AddItem(c,0.1)
			end
		end
	end	
end
UIS.InputBegan:Connect(function(Key,IsTyping)

	if Key.KeyCode == Enum.KeyCode.Q then 
		--event:FireServer()
		runservice.Heartbeat:Connect(function()
			Magnetoid()
		end)
	end
end)
1 Like

You need to disconnect it

local connection = runservice.Heartbeat:Connect(function()
   Magnetoid()
end)

task.wait(5)

connection:Disconnect()

You can use task.delay or task.wait to achieve this.
Example:

local magnetConnect = runService.HeartBeat:Connect(Magnetoid)
local duration = 5 – change this to however long you want the heartbeat to last.
task.delay(duration, function()
if magnetConnect then
magnetConnect:Disconnect()
)

If you need to tinker this the way to safely stop HeartBeats is to simply add :Disconnect()

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.