Debounce

From Goodblox Wiki
Revision as of 16:34, 22 June 2020 by Pizzaboxer (talk | contribs) (Created page with "{{CatUp|Tutorials}} __TOC__ ==Introduction== A debounce system is a system that keeps a function from running too many times. It usually is used in a listener because a liste...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Introduction

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.

The basic idea

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

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

For example:

while true do
print("Hello world1!")     -- Prints Hello world1!
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.
print("Hello world2!")
wait (5)
	enabled = true				--open up the function to be called again.
end

dosomething()  -- calls the dosomething function and prints Hello world2!
end

Debounce 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

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.