class TTY::Prompt::Timer

Attributes

duration[R]
interval[R]
total[R]

Public Class Methods

new(duration, interval) click to toggle source
# File lib/tty/prompt/timer.rb, line 11
def initialize(duration, interval)
  @duration = duration
  @interval = interval
  @total = 0.0
  @current = nil
  @events = []
end

Public Instance Methods

on_tick(&block) click to toggle source
# File lib/tty/prompt/timer.rb, line 35
def on_tick(&block)
  @events << block
end
runtime() click to toggle source
# File lib/tty/prompt/timer.rb, line 31
def runtime
  time_now - @current
end
start() click to toggle source
# File lib/tty/prompt/timer.rb, line 19
def start
  return if @current

  @current = time_now
end
stop() click to toggle source
# File lib/tty/prompt/timer.rb, line 25
def stop
  return unless @current

  @current = nil
end
time_now() click to toggle source

Object representing current time

# File lib/tty/prompt/timer.rb, line 63
def time_now
  ::Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
while_remaining() { |remaining| ... } click to toggle source
# File lib/tty/prompt/timer.rb, line 39
def while_remaining
  start
  remaining = duration

  if @duration
    while remaining >= 0.0
      if runtime >= total
        tick = duration - @total
        @events.each { |block| block.(tick) }
        @total += @interval
      end

      yield(remaining)
      remaining = duration - runtime
    end
  else
    loop { yield }
  end
ensure
  stop
end