How to Stop a function at any time?

I am currently making a gun, but I have came across a problem. When the player fires, all the firing stuff occurs. It is automatic so depends on “Button1Down” to start firing and “Button1Up” to stop. If you spam the click button, it will keep firing as the function will keep going. To fix it, I just need to stop the function while it is stilling doing its thing but I don’t know how. I already searched it and I didn’t find an answer for my problem.

mouse.Button1Down:Connect(function()
        if canfire == true and needbolt == false and aimed and cooldown == false and reloading == false and bolting == false and ammo > 0 then
			wait(0.1)
			firing = true
			while firing and equipped and cooldown == false and aimed and reloading == false do
				wait(0.12)
				-- fired shot goes here
			end
		end
end)

I am controlling that “firing” variable from somewhere else in the script. I want it so that when it changes, the function stops entirely, preventing the gun from firing after the player lets go of the click button.

use Function:Disconnect() to stop the function Completely

1 Like

using coroutines is a valuable option for this, to learn more about it Ill give you a link:
here

Make a connection to the function and then disconnect it.

Example:

local Part = script.Parent

local Connection; 

Connection = Part.Touched:Connect(function()
     print("In this example ater the part is touched it will disconnect the function")

     if Connection then -- If there's a connection
       Connection:Disconnect() -- Disconnect
    end
end)

Hope this helped

Disconnecting disables it forever I think. I just want it to stop doing what it’s doing

just add a return and it will permanently yield the thread the function is in

1 Like