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 function waits for work to finish. A channel passes values between goroutines, function calls started with go. Use select to wait for a result from a channel or a value from time.After when the time limit ends.

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 is a value passed between functions that carries a stop signal and deadline. Use context.WithTimeout for network calls so the operation can see the deadline and stop early. Use time.NewTimer when you need to cancel or reuse a timer yourself.

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