From 763f892578756f53bc2a37744bec057bc246120c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20F=C3=9CHRMANN?= Date: Sat, 18 Nov 2023 15:26:53 +0100 Subject: [PATCH] fix(stopwatch): timer was not accurate 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 --- stopwatch/stopwatch.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/stopwatch/stopwatch.go b/stopwatch/stopwatch.go index 6b298f79..7138803f 100644 --- a/stopwatch/stopwatch.go +++ b/stopwatch/stopwatch.go @@ -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,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 { @@ -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) } @@ -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 {