Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timer: fix duplicate ticks when stopping and starting fast #215

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions timer/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import (
)

var (
lastID int
idMtx sync.Mutex
lastID int
lastCycleId int
idMtx sync.Mutex
)

func nextID() int {
Expand All @@ -20,6 +21,13 @@ func nextID() int {
return lastID
}

func nextCycleID() int {
idMtx.Lock()
defer idMtx.Unlock()
lastCycleId++
return lastCycleId
}

// Authors note with regard to start and stop commands:
//
// Technically speaking, sending commands to start and stop the timer in this
Expand Down Expand Up @@ -67,6 +75,11 @@ type TickMsg struct {
// Timeout returns whether or not this tick is a timeout tick. You can
// alternatively listen for TimeoutMsg.
Timeout bool

// CycleId will indicate to which start/stop cycle a tick belongs.
// Since stopping and starting can be done in the span of less than 1s, ticks
// sent before stopping can arrive to Update, which will cause duplicate tick chains
CycleId int
}

// TimeoutMsg is a message that is sent once when the timer times out.
Expand All @@ -87,6 +100,7 @@ type Model struct {

id int
running bool
cycleId int
}

// NewWithInterval creates a new timer with the given timeout and tick interval.
Expand All @@ -96,6 +110,7 @@ func NewWithInterval(timeout, interval time.Duration) Model {
Interval: interval,
running: true,
id: nextID(),
cycleId: nextCycleID(),
}
}

Expand Down Expand Up @@ -133,13 +148,17 @@ func (m Model) Init() tea.Cmd {
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
switch msg := msg.(type) {
case StartStopMsg:

if msg.ID != 0 && msg.ID != m.id {
return m, nil
}

m.cycleId = nextCycleID()
m.running = msg.running
return m, m.tick()
case TickMsg:
if !m.Running() || (msg.ID != 0 && msg.ID != m.id) {
if !m.Running() || (msg.ID != 0 && msg.ID != m.id) ||
(msg.ID != 0 && msg.ID == m.id && msg.CycleId != m.cycleId) {
break
}

Expand Down Expand Up @@ -172,7 +191,7 @@ func (m *Model) Toggle() tea.Cmd {

func (m Model) tick() tea.Cmd {
return tea.Tick(m.Interval, func(_ time.Time) tea.Msg {
return TickMsg{ID: m.id, Timeout: m.Timedout()}
return TickMsg{ID: m.id, Timeout: m.Timedout(), CycleId: m.cycleId}
})
}

Expand Down