Skip to content

Timeouts

You can implement timeouts using select with time.After. If a channel operation doesn’t complete within the timeout, the time.After case will execute.

Wait for a channel that never sends, with a 1‑second timeout.

package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan string)
go func() {
time.Sleep(2 * time.Second)
ch <- "result"
}()
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(1 * time.Second):
fmt.Println("timeout")
}
}
Terminal window
timeout