Class: Watchcat::Debouncer
- Inherits:
-
Object
- Object
- Watchcat::Debouncer
- Defined in:
- lib/watchcat/debouncer.rb
Instance Method Summary collapse
- #clear ⇒ Object
- #debounce(key, delay_ms, &block) ⇒ Object
-
#initialize ⇒ Debouncer
constructor
A new instance of Debouncer.
- #pending_count ⇒ Object
Constructor Details
#initialize ⇒ Debouncer
Returns a new instance of Debouncer.
3 4 5 6 |
# File 'lib/watchcat/debouncer.rb', line 3 def initialize @timers = {} @mutex = Mutex.new end |
Instance Method Details
#clear ⇒ Object
28 29 30 31 32 33 |
# File 'lib/watchcat/debouncer.rb', line 28 def clear @mutex.synchronize do @timers.each_value(&:kill) @timers.clear end end |
#debounce(key, delay_ms, &block) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/watchcat/debouncer.rb', line 8 def debounce(key, delay_ms, &block) @mutex.synchronize do # Cancel existing timer for this key if @timers[key] @timers[key].kill end # Create new timer @timers[key] = Thread.new do sleep(delay_ms / 1000.0) # Convert ms to seconds @mutex.synchronize do @timers.delete(key) end block.call end end end |
#pending_count ⇒ Object
35 36 37 38 39 |
# File 'lib/watchcat/debouncer.rb', line 35 def pending_count @mutex.synchronize do @timers.size end end |