Go by Example

Timeouts

Bound how long you wait for a channel operation using time.After or context.WithTimeout inside a select.

A timeout limits how long a goroutine waits for an operation. Use select with time.After to wait for either a result or the deadline.

If the result does not arrive within one second, the timeout case runs.

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    result := make(chan string, 1)
    go func() {
        time.Sleep(200 * time.Millisecond)
        result <- "done"
    }()
    select {
    case value := <-result:
        fmt.Println(value)
    case <-time.After(time.Second):
        fmt.Println("timed out")
    }
}

In production

A context carries cancellation and deadlines through function calls. Use context.WithTimeout for network and service calls so a deadline can reach the operation; the operation must observe the context to stop early. Since Go 1.23, unreferenced timers created by time.After can be garbage collected. Use time.NewTimer when explicit cancellation or reuse is needed.

Enjoyed this? Get more software craft delivered to your inbox.