So I have this code, it accepts user entry of one
, two
, or three
. It prints Ticker ticked
depending on the duration selected. I need help on how to stop the ticker first before activating the ticker again with a different duration.
package main
import (
"bufio"
"fmt"
"os"
"strings"
"time"
)
func main() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
switch text {
case "one":
go timeTick(true, 1)
case "two":
go timeTick(true, 2)
case "three":
go timeTick(true, 3)
default:
go timeTick(false, 0)
}
}
}
func timeTick(flag bool, tick int) {
var tickChan *time.Ticker
if flag {
tickChan = time.NewTicker(time.Second * time.Duration(tick))
}
doneChan := make(chan bool)
if !flag {
doneChan <- true
}
for {
select {
case <-tickChan.C:
fmt.Println("Ticker ticked")
case <-doneChan:
fmt.Println("Done")
return
}
}
}
So user inputs either, one
, two
, or three
to activate the ticker else it will send true
to doneChan
channel.
When I activated the ticker with one
. It prints Ticker ticked
every second but how do I stop the ticker when I input two
or three
while the ticker is running? It then brings me to my main question, why is doneChan
not triggered at all even inputting a random string?