Your timeout will not happen, because one of your goroutine sends a value to your c1 channel every 1.5 seconds (or so), and your timeout will only happen if there is no value that will be received from c1 in within 2 seconds.
As soon as the value is obtained from c1 , in the next iteration that executes select , the new time.After() call will be called again, which returns a new channel through which the value will be sent only after 2 seconds. The timeout channel from the previous select execution is discarded and is no longer used.
To get a timeout after 2 seconds, create a timeout channel only once, for example:
timeout := time.After(2000 * time.Millisecond) for { select { case i := <-c1: fmt.Println(i) case <-timeout: fmt.Println("TIMEOUT")
Output:
10 TIMEOUT 10 10 10 ...
source share