Channel Timeouts
Start with Channel Timeouts
In this lesson, explore channel timeouts through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of channel timeouts.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use select with a timer channel to bound how long a caller waits. time.NewTimer makes ownership and cleanup explicit; time.After offers a concise one-shot alternative.
A timeout stops waiting for a result; it does not necessarily stop the goroutine doing the work. Pair timeouts with cancellation when resources matter.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"time"
)
func main() {
results := make(chan int, 1)
results <- 9
timer := time.NewTimer(time.Hour)
defer timer.Stop()
select {
case value := <-results:
fmt.Println("Result:", value)
case <-timer.C:
fmt.Println("Timed out")
}
}
Output
Result: 9Trace what the program does
The buffered result is already available, while the timer is not. The select prints Result: 9 and stops the unused timer.
Avoid common mistakes
- A caller timeout is not a worker cancellation signal.
- Avoid relying on millisecond race conditions for deterministic teaching output.
Try it yourself
Add a worker that waits on context cancellation after the timeout instead of continuing unbounded work.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Channel Timeouts in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.