Sha256: ddc9babad56448d252e5f079694e7ab8d8468931c310ca6b1e6ee3d8249cc3dd

Contents?: true

Size: 564 Bytes

Versions: 1

Compression:

Stored size: 564 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 && (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

  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.0 lib/proc/throttle.rb