To pause the execution of a current program in Go, delay code execution, and wait for a specified period of time, you just need to use the Sleep()
function defined in the time package. As an argument, this function takes a variable of type time.Duration
, which is the amount of time the program execution should be stopped for. It can be expressed as a number multiplied by a unit constant. For example 3*time.Second
means that the execution will be stopped for 3 seconds. Available units are:
time.Nanosecond
time.Microsecond
time.Millisecond
time.Second
time.Minute
time.Hour
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("before Sleep()")
time.Sleep(3 * time.Second)
fmt.Println("waking up after Sleep()")
}