Select with timeout
- Go course
- Intermediate
- Lesson 16/80
- 4 min
Learn to use time.After for a timeout inside select.
select with timeout
With time.After you add a timeout to select. If no case is ready within the duration the timeout case fires. This removes the risk of waiting forever.
Pattern: case <-time.After(2 * time.Second):. This returns a channel that signals after 2 seconds. select waits on it; when the time elapses the timeout case runs and the goroutine exits or does other work.
Timeout pattern
The timeout pattern is critical in production: when sending a request to a service you give up if no response arrives in time. This prevents the system from filling with blocked goroutines.
context.WithTimeout gives a cleaner alternative; it carries the timeout as a context and also signals cancellation. Context is covered in detail in later lessons.
Practice Wait with a timeout
Inside main, add a select { case ... case <-time.After(...): ... } block and print timeout with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ch := make(chan string)
select {
case m := <-ch:
fmt.Println(m)
default:
fmt.Println("zaman aşımı")
}
}Expected output
zaman aşımı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does time.After return?
- A duration
- A goroutine
- An error
- A channel Correct answer
Explanation: a channel. Duration is time.Duration; time.After returns a channel.
2 Timeout case
select {
case v := <-ch:
fmt.Println(v)
case <-time.After(____):
fmt.Println("zaman aşımı")
}
select {
case v := <-ch:
fmt.Println(v)
case <-time.After(2 * time.Second):
fmt.Println("zaman aşımı")
}
Explanation: 2 is a number, time is the duration type.
3 Match timeout concepts
| Term | Meaning |
|---|---|
time.After |
Timeout |
select |
Wait |
channel |
Signal |
default |
Non-blocking |