Class: Watchcat::Debouncer

Inherits:
Object
  • Object
show all
Defined in:
lib/watchcat/debouncer.rb

Instance Method Summary collapse

Constructor Details

#initializeDebouncer

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

#clearObject



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_countObject



35
36
37
38
39
# File 'lib/watchcat/debouncer.rb', line 35

def pending_count
  @mutex.synchronize do
    @timers.size
  end
end