Sha256: fce05712de95f2a72f4d47d501892097237d71e3ba9effc09b9591d588b7db3d

Contents?: true

Size: 588 Bytes

Versions: 1

Compression:

Stored size: 588 Bytes

Contents

class Proc
  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
        if (last_exec.nil? || (last_exec + delay_sec < now))
          self.call(*args)
          last_exec = now
        end
      else
        thread = Thread.new do
          sleep(delay_sec)
          self.call(*args)
          last_exec = Time.now.to_f
        end
      end
    end
  end

  def debounce(delay_sec)
    throttle(delay_sec, true)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
proc-throttle-0.1.1 lib/proc/throttle.rb