How do I stop a function once I dont want to use it anymore?

I am making a game where events with a timer system happen and stuff. This event is just a find the button event. But when this event happens multiple times, the function from the last event is still going on. How do I cancel a function?

I want to cancel the “ButtonEventPress.MouseClick” one

1 Like

You can disable a function by disconnecting it.
For example:

--//Variables
local Part = workspace.Part

--//Tables
local Connections = {}

--//Functions
Connections[Part] = Part.Touched:Connect(function(hit)
	local Humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid")
	
	if Humanoid then
		Humanoid.Health -= 25
		
		Connections[Part]:Disconnect()
	end
end)

(you can send me your code and I can fix it for you if you don’t understand.)

2 Likes

Use a debouce

findbutton = function()
   -- ...
   local connection
   connection = ...buttonEventPress.MouseClick:Connect(function(plr)
      connection:Disconnect()
   end)
end,
1 Like

This works, thanks. I was looking for a solution