Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
fuhrmannb committed Nov 18, 2023
1 parent 167e906 commit 98f46b6
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions stopwatch/stopwatch.go
Original file line number Diff line number Diff line change
@@ -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

@@ -118,7 +119,14 @@ 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 {
return m, nil
@@ -128,7 +136,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)
}

@@ -137,12 +144,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 {

0 comments on commit 98f46b6

Please sign in to comment.