Debounce

From Legacy Roblox Wiki
Revision as of 02:36, 6 August 2007 by >Clockwork
Jump to navigationJump to search

A debounce system is a system that keeps a function from running too many times. It usually is used in a listener because a listener can be called many times while it's still working.

A debounce system usually works like this:

enabled = true					--default is true, so that the function works
function dosomething()
	if not enabled then return end		--if enabled is not true, then return without doing anything.
	enabled = false				--set enabled to false, because this function is already doing something.
	--stuff is done here			
	enabled = true				--open up the function to be called again.
end

So debouncing works by setting the "gate" variable (in this case, enabled) to false while it's performing the stuff it needs to do so that it won't get interrupted. After it's finished, it sets it back to true so that it can run again later.

Let's take a look at how debounce works in a real script. Here's the Local Gui script of the Rocket Launcher:

enabled = true
function onButton1Down(mouse)
	if not enabled then
		return
	end

	enabled = false
	mouse.Icon = "rbxasset://textures\\GunWaitCursor.png"

	wait(12)
	mouse.Icon = "rbxasset://textures\\GunCursor.png"
	enabled = true

end

So, when you fire a rocket, the script shows the reload icon. Then the function waits for 12 seconds. During this time, enabled is false, so if the player tries to fire another rocket, the script won't run because the function will just return right away. After the 12 seconds are up, the reload cursor goes away and enabled becomes true again, allowing the user to fire another rocket.