Skip to content

Instantly share code, notes, and snippets.

@alhafoudh
Last active December 1, 2017 12:20
Show Gist options
  • Save alhafoudh/e1ccfa0020643df2495614ed21cdb9b0 to your computer and use it in GitHub Desktop.
Save alhafoudh/e1ccfa0020643df2495614ed21cdb9b0 to your computer and use it in GitHub Desktop.
class Throttler
attr_reader :period
attr_reader :value
attr_reader :block
def initialize(period)
@period = period
@first_time = nil
@value = nil
@block = proc { }
end
def throttled(&block)
@block = block if @block.nil?
if @first_time.nil?
@value = block.call
@first_time = Time.now
end
current_time = Time.now
@last_time = current_time unless last_time
delta_time = current_time - last_time
if delta_time > @period
@value = block.call
@last_time = current_time
end
value
end
def stop
block.call
end
private
attr_reader :last_time
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment