Is there a better way not to cause an infinite loop within a property change function that changes the connected property in the function itself

So as shown in the code below and as per title, is there a better way?

I’m feeling as if I could avoid this somehow if I was a better programmer or there’s some method to do this without disconnecting and reconnecting a function like shown below

Thanks

local function onBoltedChanged(newValue)
	print(newValue)
	
	local boltedDuration = 5
	
	if not bolted.Value then
		bolted.Value = true
		task.wait(boltedDuration)
		connection:Disconnect()
		bolted.Value = false
	end
	connection = model.Bolted.Changed:Connect(onBoltedChanged)
end


connection = model.Bolted.Changed:Connect(onBoltedChanged)


2 Likes

You can create a debounce

local debounce = false
local function onBoltedChanged(newValue)
	print(newValue)
	
	local boltedDuration = 5
	
	if not bolted.Value then
		if debounce == true then return end
		debounce = true

		bolted.Value = true
		task.wait(boltedDuration)
		bolted.Value = false
		
		debounce = false
	end
end

model.Bolted.Changed:Connect(onBoltedChanged)
1 Like

I am not sure why you are connecting/disconnecting the function.

Here are 2 suggestions:

model = game.Workspace:WaitForChild("Model")
local bolted = model:WaitForChild("Bolted")
local boltedDuration = 5


local function onBoltedChanged(newValue)
	
	print(newValue)

	if not bolted.Value then
		bolted.Value = true
		task.wait(boltedDuration)
		bolted.Value = false
	end
end
bolted.Changed:Connect(onBoltedChanged)



--========
-- OPTION
--========

-- Collects all models in Workspace and checks for Bolted

for _, item in pairs(game.Workspace:GetChildren()) do
	if item:IsA("Model") then
		if item:FindFirstChild("Bolted") then
			
			local function onBoltedChanged(newValue)
				
				print(newValue)

				if not bolted.Value then
					bolted.Value = true
					task.wait(boltedDuration)
					bolted.Value = false
				end
			end
			bolted.Changed:Connect(onBoltedChanged)
			
		end
	end
end

He is disconnecting it because when he changes the value, the .Changed signal is fired again. Using debounce would stop it.

1 Like