Skip to content

Commit

Permalink
fix: stop and drain timers (#993)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 committed May 3, 2024
1 parent f946f1a commit 0c937f4
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,16 @@ type sequenceMsg []Cmd
//
// Every is analogous to Tick in the Elm Architecture.
func Every(duration time.Duration, fn func(time.Time) Msg) Cmd {
n := time.Now()
d := n.Truncate(duration).Add(duration).Sub(n)
t := time.NewTimer(d)
return func() Msg {
n := time.Now()
d := n.Truncate(duration).Add(duration).Sub(n)
t := time.NewTimer(d)
return fn(<-t.C)
ts := <-t.C
t.Stop()
for len(t.C) > 0 {
<-t.C
}
return fn(ts)
}
}

Expand Down Expand Up @@ -141,9 +146,14 @@ func Every(duration time.Duration, fn func(time.Time) Msg) Cmd {
// return m, nil
// }
func Tick(d time.Duration, fn func(time.Time) Msg) Cmd {
t := time.NewTimer(d)
return func() Msg {
t := time.NewTimer(d)
return fn(<-t.C)
ts := <-t.C
t.Stop()
for len(t.C) > 0 {
<-t.C
}
return fn(ts)
}
}

Expand Down

0 comments on commit 0c937f4

Please sign in to comment.