Last active
December 1, 2017 12:20
-
-
Save alhafoudh/e1ccfa0020643df2495614ed21cdb9b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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