How can I kill a thread within the code below without duplicated the event created?

  1. What do you want to achieve?

I want to kill a thread from running when a condition is true.

  1. What is the issue?

I manage to kill the thread, but it seems like the event I created is still recognized/not dead.

  1. What solutions have you tried so far?

I have heard about the task.cancel() method, but I am not very confident in using it within my script or finding a thread that clearly explains how to use task.cancel().

local function someFunction()
	local dead = false
	
	local function killThread()
		dead = true
		print("dead")
	end
	
	tool.Unequipped:Connect(killThread) -- not sure how to kill this line

	wait(seconds)

	if dead == false then
		--Execute code here
	end
end

Although this satisfied the condition of killing the thread, “gunMechanic.Weapon.Unequipped:Connect(killThread)” does not and will stack upon each time I unequip my tool (Unequipped first time = print “dead” 1x, Unequipped second time = print “dead” 2x, etc).

How do I stop this from happening?

I just found out how that disconnect() method exists in which I can store the method as a variable. Though I know about this, where is the best place I can put my disconnect in the script?

This is me after 30 minutes later: “On second thought, I just solved the problem after a couple of minutes. Just in case someone is curious about what the solution is, I can create a temporary variable to store the connection of the kill function. Then, inside the function, I can use the temporary variable to disconnect the connection. If anyone can find a better solution let me know.”

local function someFunction()
	local dead = false

	local currentConnection
	
	currentConnection = tool.Unequipped:Connect(function()
		dead = true
		print("dead")
		currentConnection:Disconnect
	)

	wait(seconds)

	if dead == false then
		--Execute code here
	end
end

I know kinda late but instead of using :Connect use :Once it will do the exact samething that your function is doing