Class: Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/tabscroll/timer.rb

Overview

A simple timer that counts in seconds.

Usage:

timer = Timer.new
timer.start
...
if timer.delta > 0.5 # half a second
    ...

Instance Method Summary collapse

Constructor Details

#initializeTimer

Returns a new instance of Timer.



12
13
14
15
# File 'lib/tabscroll/timer.rb', line 12

def initialize
  @is_running = false
  @is_paused  = false
end

Instance Method Details

#deltaObject

Returns the current delta in seconds (float).



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/tabscroll/timer.rb', line 67

def delta
  if @is_running
    return (Time.now.to_f - @start_time.to_f)
  end

  return @paused_time.to_f if @is_paused

  return @start_time if @start_time == 0 # Something's wrong

  return (@stop_time.to_f - @start_time.to_f)
end

#pauseObject



42
43
44
45
46
47
48
# File 'lib/tabscroll/timer.rb', line 42

def pause
  return if not @is_running or @is_paused

  @paused_time = (Time.now - @start_time)
  @is_running  = false
  @is_paused   = true
end

#paused?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/tabscroll/timer.rb', line 62

def paused?
  @is_paused
end

#restartObject



37
38
39
40
# File 'lib/tabscroll/timer.rb', line 37

def restart
  self.stop
  self.start
end

#running?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/tabscroll/timer.rb', line 58

def running?
  @is_running
end

#startObject

Starts counting.



18
19
20
21
22
23
24
25
26
# File 'lib/tabscroll/timer.rb', line 18

def start
  return if @is_running

  @start_time  = Time.now
  @stop_time   = 0.0
  @paused_time = 0.0
  @is_running  = true
  @is_paused   = false
end

#stopObject

Stops counting.



29
30
31
32
33
34
35
# File 'lib/tabscroll/timer.rb', line 29

def stop
  return if not @is_running

  @stop_time  = Time.now
  @is_running = false
  @is_paused  = false
end

#to_sObject

Converts the timer’s delta to a formatted string.



80
81
82
83
84
85
86
# File 'lib/tabscroll/timer.rb', line 80

def to_s
  min  = (self.delta / 60).to_i
  sec  = (self.delta).to_i
  msec = (self.delta * 100).to_i

  "#{min}:#{sec}:#{msec}"
end

#unpauseObject



50
51
52
53
54
55
56
# File 'lib/tabscroll/timer.rb', line 50

def unpause
  return if not @is_paused or @is_running

  @start_time = (Time.now - @paused_time)
  @is_running = true
  @is_paused  = false
end