Class: Proc
- Inherits:
-
Object
- Object
- Proc
- Defined in:
- lib/proc/throttle.rb
Instance Method Summary collapse
Instance Method Details
#debounce(delay_sec) ⇒ Object
26 27 28 |
# File 'lib/proc/throttle.rb', line 26 def debounce(delay_sec) throttle(delay_sec, true) end |
#throttle(delay_sec, debounce = false) ⇒ Object
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/proc/throttle.rb', line 2 def throttle(delay_sec, debounce = false) thread = nil last_exec = nil Proc.new do |*args| now = Time.now.to_f if thread && thread.alive? thread.kill end if !debounce && (last_exec.nil? || (last_exec + delay_sec < now)) self.call(*args) last_exec = now else thread = Thread.new do sleep(delay_sec) self.call(*args) last_exec = Time.now.to_f end end end end |