Skip to content

Commit

Permalink
fix(stopwatch): timer was not accurate
Browse files Browse the repository at this point in the history
Stopwatch does not track correctly time since update process time can be
longer that tick time update.

This patch adds a start time with `sT` attribute to track time of
stopwatch start.

Also adapt view to have accuracy matching the tick interval. To have
directly the raw duration value, use `Elapsed()` method.

Issue: #237
  • Loading branch information
fuhrmannb committed Nov 18, 2023
1 parent 167e906 commit 763f892
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions stopwatch/stopwatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type ResetMsg struct {
// Model for the stopwatch component.
type Model struct {
d time.Duration
sT time.Time
id int
running bool

Expand Down Expand Up @@ -118,6 +119,12 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if msg.ID != m.id {
return m, nil
}
if msg.running && !m.running {
m.sT = time.Now()
}
if !msg.running && m.running {
m.d += time.Since(m.sT)
}
m.running = msg.running
case ResetMsg:
if msg.ID != m.id {
Expand All @@ -128,7 +135,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
if !m.running || msg.ID != m.id {
break
}
m.d += m.Interval
return m, tick(m.id, m.Interval)
}

Expand All @@ -137,12 +143,15 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {

// Elapsed returns the time elapsed.
func (m Model) Elapsed() time.Duration {
if m.running {
return m.d + time.Since(m.sT)
}
return m.d
}

// View of the timer component.
func (m Model) View() string {
return m.d.String()
return m.Elapsed().Round(m.Interval).String()
}

func tick(id int, d time.Duration) tea.Cmd {
Expand Down

0 comments on commit 763f892

Please sign in to comment.