Skip to content

Instantly share code, notes, and snippets.

@opyate
Last active February 24, 2023 15:11
Show Gist options
  • Save opyate/9fbaa15d976208b5712525ca4361e76d to your computer and use it in GitHub Desktop.
Save opyate/9fbaa15d976208b5712525ca4361e76d to your computer and use it in GitHub Desktop.
Godot 3 debouncer, tested on 3.5.1

Yes, I know... who needs a debouncer in Godot, right? 😂

¯\_(ツ)_/¯

Other ideas: the debouncer call can also accept arguments, and call with the last-received args, or even accumulate all args, and call your_func with that.

class Debounce:
var _tree: SceneTree
var _timer: SceneTreeTimer
var _wait: float
var _fn: FuncRef
func _init(tree: SceneTree, fn: FuncRef, wait: float = 0.15):
_tree = tree
_fn = fn
_wait = wait
func _refresh_timer():
if _timer and _timer.is_connected("timeout", self, "_on_timeout"):
_timer.disconnect("timeout", self, "_on_timeout")
_timer = _tree.create_timer(_wait)
# warning-ignore:RETURN_VALUE_DISCARDED
_timer.connect("timeout", self, "_on_timeout")
func call():
_refresh_timer()
func _on_timeout():
_fn.call_func()
onready var debouncer: Debounce = Debounce.new(get_tree(), funcref(self, "your_func"))
# elsewhere in code
func im_called_in_bursts():
debouncer.call()
func your_func():
print("just had a burst")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment