×

go · level 3 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

time.After gives you a channel that fires once, after a delay.

Real work can hang: a server never answers, a disk is slow. time.After(50 * time.Millisecond) returns a channel that receives one value once 50 milliseconds have passed. Put it in a select beside the real work, and whichever is ready first wins. That limit on waiting is a .

time.Millisecond and time.Second are each a duration, so 2 * time.Second reads like English. Go prints them neatly too: fmt.Println(1500 * time.Millisecond) shows 1.5s.

Timings change from run to run and from computer to computer, so never print how long something took in a result you compare. Print what happened: finished, or timed out.

package main
import (
	"fmt"
	"time"
)
func fetch(reply chan string) {
	time.Sleep(time.Second)
	reply <- "page loaded"
}
func main() {
	reply := make(chan string, 1)
	go fetch(reply)
	select {
	case r := <-reply:
		fmt.Println(r)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("gave up waiting")
	}
}

The buffer of 1 lets fetch finish its send later even though nobody is listening any more.