Debounce
A debounce prevents a function from running too many times or an input triggering multiple times. The follow is some good examples on when to use debounces.
Detect a collision
Individual cooldowns
If you want to create a kill brick, you will need to use the .Touched event and damage the player. However since we don't have a debounce, this will damage the player many times as it is running every frame.
local part = script.Parent
part.Touched:Connect(function(hit)
if not hit:IsA("Player") then return end
hit.Health = hit.Health - 10
end)
To avoid causing excessive damage, we will add a debounce pattern which adds a cooldown to our function.
In this example, we use a debounce table so that each player has their own individual cooldowns.
local part = script.Parent
local debounce = {} -- Create a debounce table
local debounceTime = 1 -- Set a debounce time
part.Touched:Connect(function(hit)
if not hit:IsA("Player") then return end
if debounce[hit] then return end
debounce[hit] = true
hit.Health = hit.Health - 10
wait(debounceTime)
debounce[hit] = nil
end)
Global cooldowns
If you want to create a door, you would want the cooldown to be global so that the door only opens after the cooldown for everybody.
local zone = script.Parent
local debounce = false -- Create a debounce boolean
local debounceTime = 1 -- Set a debounce time
zone.Touched:Connect(function(hit)
if not hit:IsA("Player") then return end
if debounce then return end
debounce = true
--- DOOR ACTION HERE ---
wait(debounceTime)
debounce = nil
end)