Skip to content

Timers

A time.Timer represents a single event in the future. You can wait for it on its channel (<-timer.C) or stop it before it fires.

Create a timer that fires after 2 seconds.

package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(2 * time.Second)
fmt.Println("Waiting...")
<-timer.C
fmt.Println("Timer fired")
// Stopping a timer
timer2 := time.NewTimer(1 * time.Second)
stop := timer2.Stop()
if stop {
fmt.Println("Timer2 stopped before firing")
}
}
Terminal window
Waiting...
Timer fired
Timer2 stopped before firing