How to Make a Cooldown With Two Loops

Hi everyone! So I have this script that makes a part move at a random time or when a player clicks a button. They are two separate parts of the script and both work fine when alone. but when together, the while true do loop works whilst the ButtonPress doesn’t work. Here is the code (not the full code, but the buggy part):

-- While loop
while true do
	wait(math.random(35, 70))
	CeilingFalling()
end

-- ButtonPress loop

local debounce = false

ButtonClick.MouseClick:Connect(function()
	if debounce == false then
		debounce = true
		CeilingFalling()
		delay(15, function()
			debounce = false
		end)
	end	
end)

What I can’t manage to do is to make it so that when a player presses the button, it restarts the random timer as well so the button can’t be pressed at the same time as the function is called in the while loop. I also want to make it so the time restarts in the ButtonPressed when the function is called in the while loop.

You need to move the while loop to the bottom. Loops act like “walls” to code underneath the bodies, since the underneath code won’t execute until the loop has terminated. So you are preventing the debounce variable from ever being declared and the connection to MouseClick from ever being created.

1 Like

Thank you! But that doesn’t fix my problem, since i can press the button while the loop is being done which then ends up making the variable happen twice at the same time

I solved it. Thank you for the help !