go · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The answer is already waiting. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import (
"fmt"
"time"
)
func main() {
reply := make(chan string, 1)
reply <- "cached answer"
limit := time.Second
select {
case r := <-reply:
fmt.Println(r)
case <-time.After(limit):
fmt.Println("timed out")
}
fmt.Println("limit was", limit)
}
your turn
Your turn. Do not burn the toast.
The toast takes 20 milliseconds. Choose a timeout of at least one second, such as 2 * time.Second, so the toast always wins.
output
press run to see what happens
fix it
The virus scan always times out. Can you fix it?
output
press run to see what happens
- The scan takes 200 milliseconds, yet the timeout wins every time. How long is
500on its own? - A bare number used as a duration counts nanoseconds, billionths of a second. 500 of those is next to nothing.
- Write
time.After(500 * time.Millisecond).
nailed it
your program knows when to give up. :D
time.After(d)is a channel that fires once afterd.- Race the work against it in a
select. - Never put measured times in output you compare.
new words in your collection
- timeout
This lesson isn’t saved. A free account remembers every lesson you finish.