MouseButton1Click Memory Leak

There are 2 functions that have the same MouseButton function, but every time I go to the second one after the first, it simultaneously runs both.

Like this:

function DeliverText(text, value, text2)
	mainFrame.TextFrame.Visible = true	
	Module.Render(mainFrame.TextFrame.Frame.TextLabel,text,0.05,false)
	wait(1)
	if value == true then
		mainFrame.TextFrame.Accept.Visible = true
		mainFrame.TextFrame.Cancel.Visible = true
	end

	local function cancel()
		mainFrame.TextFrame.Visible = false

		mainFrame.TextFrame.Accept.Visible = false
		mainFrame.TextFrame.Cancel.Visible = false
		replicatedStorage:WaitForChild("AllowShop"):FireServer(false)
	end

	local function accept()
		mainFrame.TextFrame.Accept.Visible = false
		mainFrame.TextFrame.Cancel.Visible = false
		
		Module.Render(mainFrame.TextFrame.Frame.TextLabel,text2,0.05,false)
	
		wait(2)
		mainFrame.TextFrame.Visible = false
		replicatedStorage:WaitForChild("AllowShop"):FireServer(true)
		
	end

	mainFrame.TextFrame.Accept.MouseButton1Click:Connect(accept)
	mainFrame.TextFrame.Cancel.MouseButton1Click:Connect(cancel)
end

The second is basically a copied and pasted version of the first. I also tried putting return at the end of the function, but it does absolutely nothing. How do I fix this memory leak?

That’s because the events still fire, because they’re still connected to that function. In order to disconnect it, you use :Disconnect(). Like this:

function DeliverText(text, value, text2)
	mainFrame.TextFrame.Visible = true	
	Module.Render(mainFrame.TextFrame.Frame.TextLabel,text,0.05,false)
	wait(1)
	local Connection1 = nil
	local Connection2 = nil

	if value == true then
		mainFrame.TextFrame.Accept.Visible = true
		mainFrame.TextFrame.Cancel.Visible = true
	end

	local function cancel()
		mainFrame.TextFrame.Visible = false

		mainFrame.TextFrame.Accept.Visible = false
		mainFrame.TextFrame.Cancel.Visible = false
		replicatedStorage:WaitForChild("AllowShop"):FireServer(false)
		Connection1:Disconnect()
		Connection2:Disconnect()
	end

	local function accept()
		mainFrame.TextFrame.Accept.Visible = false
		mainFrame.TextFrame.Cancel.Visible = false
		
		Module.Render(mainFrame.TextFrame.Frame.TextLabel,text2,0.05,false)
	
		wait(2)
		mainFrame.TextFrame.Visible = false
		replicatedStorage:WaitForChild("AllowShop"):FireServer(true)
		Connection1:Disconnect()
		Connection2:Disconnect()
	end

	Connection1 = mainFrame.TextFrame.Accept.MouseButton1Click:Connect(accept)
	Connection2 = mainFrame.TextFrame.Cancel.MouseButton1Click:Connect(cancel)
end

Thanks for the solution! It took me over an hour to solve this! :smiley: