1+package main2+3+// This example illustrates how to debounce commands.4+//5+// When the user presses a key we increment the "tag" value on the model and,6+// after a short delay, we include that tag value in the message produced7+// by the Tick command.8+//9+// In a subsequent Update, if the tag in the Msg matches current tag on the10+// model's state we know that the debouncing is complete and we can proceeed as11+// normal. If not, we simply ignore the inbound message.12+13+import (14+ "fmt"15+ "os"16+ "time"17+18+ tea "github.com/charmbracelet/bubbletea"19+)20+21+const debounceDuration = time.Second22+23+type exitMsg int24+25+type model struct {26+ tag int27+}28+29+func (m model) Init() tea.Cmd {30+ return nil31+}32+33+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {34+ switch msg := msg.(type) {35+ case tea.KeyMsg:36+ // Increment the tag on the model...37+ m.tag++38+ return m, tea.Tick(debounceDuration, func(_ time.Time) tea.Msg {39+ // ...and include a copy of that tag value in the message.40+ return exitMsg(m.tag)41+ })42+ case exitMsg:43+ // If the tag in the message doesn't match the tag on the model then we44+ // know that this message was not the last one sent and another is on45+ // the way. If that's the case we know, we can ignore this message.46+ // Otherwise, the debounce timeout has passed and this message is a47+ // valid debounced one.48+ if int(msg) == m.tag {49+ return m, tea.Quit50+ }51+ }52+53+ return m, nil54+}55+56+func (m model) View() string {57+ return fmt.Sprintf("Key presses: %d", m.tag) +58+ "\nTo exit press any key, then wait for one second without pressing anything."59+}60+61+func main() {62+ if err := tea.NewProgram(model{}).Start(); err != nil {63+ fmt.Println("uh oh:", err)64+ os.Exit(1)65+ }66+}