Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท UI and Events

Buttons and Events: Connect, Once, Wait and Disconnect

Understand Roblox events and signals: connect a function to a button click, listen once, wait for an event, disconnect, and debounce repeated clicks.

Scripts that run top to bottom once are not very interactive. Games need to react: a player clicks a button, touches a part, joins the server, or changes a property. Roblox handles this with events. An event is a signal that an instance fires when something happens, and your script can connect a function to it.

This lesson covers events from the point of view of a button, but everything here works for any event in Roblox. Roblox code is shown read-only. The runnable parts are a JavaScript Signal class that behaves like a Roblox event, so you can experiment with Connect, Once, Wait and Disconnect right here.

Connecting a function

Every event has a Connect method. You pass a function, and Roblox calls it each time the event fires, handing it the event's arguments.

LUA
-- LocalScript inside a TextButton
local button = script.Parent

local function onClick()
	print("Button was clicked!")
	button.Text = "Thanks!"
end

button.Activated:Connect(onClick)

Note the colon in button.Activated:Connect(...). Activated is the event, and Connect is a method called on it. You are not calling onClick(); you pass the function itself so the engine can call it later.

You can also pass an anonymous function:

LUA
button.Activated:Connect(function(inputObject)
	print("Clicked with", inputObject.UserInputType)
end)

Which button event?

  • Activated fires for a click, a tap or a gamepad press. Use this one for most buttons because it works on every device.
  • MouseButton1Click fires for left mouse clicks and touch taps, but not for gamepads.
  • MouseEnter and MouseLeave fire when the cursor moves over or off the object (useful for hover effects on PC).
  • InputBegan and InputEnded give raw input details for custom controls.

Many other classes have events too. Part.Touched fires when something touches a part, Players.PlayerAdded when someone joins, Humanoid.Died when a character dies, and every instance has GetPropertyChangedSignal("Name") to react to a property change.

LUA
humanoid.HealthChanged:Connect(function(newHealth)
	healthBar.Size = UDim2.fromScale(newHealth / humanoid.MaxHealth, 1)
end)

Connections, Disconnect and Once

Connect returns a connection object. Keep it if you want to stop listening later.

LUA
local connection
connection = button.Activated:Connect(function()
	print("Only the first click counts")
	connection:Disconnect()
end)

Because that pattern is so common, Roblox adds Once, which disconnects automatically after the first call:

LUA
button.Activated:Once(function()
	print("This runs a single time")
end)

And Wait pauses the current thread until the event fires, returning its arguments:

LUA
local player = Players.PlayerAdded:Wait()
print(player.Name .. " joined")

Four ways to use an event

Connect Run a function every time.
Once Run a function one time.
Wait Pause until it fires.
Disconnect Stop listening.

Keep the connection if you need Disconnect later.

1 / 2

A Signal you can run

Roblox's real engine events are built in, but the idea is simple enough to model in JavaScript. This stand-in has the same four methods. Run it and read the log carefully.

JS A Roblox-style Signal (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the output: Once only reacted to click 1, Connect reacted to clicks 1 and 2 but not 3, and Wait resumed on click 4.

Debounce: ignoring repeated clicks

A player can click a button many times a second, and a touch part can fire Touched dozens of times as a character walks across it. A debounce is a flag or timestamp that makes extra calls do nothing for a short while.

LUA
local COOLDOWN = 2
local lastUse = 0

button.Activated:Connect(function()
	if os.clock() - lastUse < COOLDOWN then
		return
	end
	lastUse = os.clock()
	print("Action runs")
end)
JS Debounce with a timestamp

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Clicks at 500 and 1500 ms are ignored, the click at 2000 ms is accepted (two seconds have passed), and so on.

Common mistakes

  • Calling the function instead of passing it. button.Activated:Connect(onClick()) runs it immediately and connects nil. Write Connect(onClick).
  • Using . instead of :. signal.Connect(fn) fails; Luau methods need a colon.
  • Leaking connections. Connections to objects that get destroyed are cleaned up, but connections to long-lived objects (such as Players or RunService) keep running. Disconnect them when done.
  • Heavy work inside Touched. It can fire many times per second. Use a debounce.
  • Expecting events to wait for each other. Each connected function runs in its own thread, so a slow handler does not block the others.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event is the best choice for a button that must work on PC, phone and gamepad?

    Activated fires for mouse clicks, touch taps and gamepad presses.
  2. 2. What does button.Activated:Once(fn) do?

    Once connects the function and disconnects it right after the first call.
  3. 3. What is wrong with: button.Activated:Connect(onClick())

    Parentheses call the function. Connect expects the function itself.
  4. 4. What is a debounce used for?

    A debounce stores a flag or timestamp so that rapid repeated events do not run the action again straight away.

Summary

  • An event fires when something happens; Connect registers a function that runs each time, with the event's arguments.
  • Use Activated for buttons so every device works.
  • Connect returns a connection you can Disconnect; Once disconnects itself; Wait pauses until the event fires.
  • Use a debounce to ignore rapid repeats, especially for Touched.
  • You pass the function, you do not call it.

Next: BindableEvents and ModuleScripts