How do I make the function stop from carrying on once the event is fired?

Basically, I want the function to stop running completely when the event is fired. Currently, the event does get fired but the loop continues.

local timerOn = false
function startTimer(team)
	if not timerOn then
		timerOn = true
		spawn(function()
			currentTeam.Changed:connect(function()
				timerOn = false
				return
					
			end)
			
			for i = 0,timer do
				
				print(i)
				wait(1)
				if i == timer then
					
					print("worked")
					timerOn = false
					
				end
				
			end
		end)
	end
end
2 Likes

Simply Disconnect the Connection, you may need to define the variable beforehand to hold the RBXScriptConnection.
Wrap it in a do block for extra clean syntax!

For example:

local Connection do
    Connection = RBXScriptSignal:Connect(function()
        Connection:Disconnect();
    end)
end
1 Like

Does disconnecting it make it so it’s unusable forever?

1 Like

Only that connection. Events may have multiple listeners, so it can always be reconnected. However you are good since you don’t connect to the same event more than once

1 Like

I’m sorry but am I doing something wrong?

image

1 Like

Disconnect will only prevent the listener from being fired again should the conditions for it being fired be met. It doesn’t interrupt nor stop a function mid-execution like OP wants (or so I’m assuming).

1 Like

RBXScriptSignal was really just a subtitute for your event (currentTeam.Changed) .

Your code would look like:

local Connection do
    Connection = currentTeam.Changed:Connect(function()
        timerOn = false;
        Connection:Disconnect();
    end)
end
1 Like

Yea, I need the script to stop but it can be fired again. Basically the event is acting as a check if the loop should keep going.

1 Like

Wouldn’t that only stop that event from being fired once again?

1 Like

Whoops, I thought you wanted to stop the Connection.
Couldn’t you just use a conditional if statement to see if timerOn is false in the for loop?
If so, return of course.

2 Likes

Yea, I thought of that when you wrote out the disconnect part but I tried your way as it seemed like a cleaner way to do it. Anyways, it works. Thanks.

2 Likes