DEV Community

Cover image for 3 examples of sleeping in Go
Onelinerhub
Onelinerhub

Posted on

3 examples of sleeping in Go

In order to sleep, we need time lib. Simplest case, when we want to sleep for a single second, we do it like:

package main
import "time"

func main() {
  // ...
  time.Sleep(time.Second)
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Sleep for seconds

In order to sleep for several seconds, we multiple by the amount of second we need. E.g. to sleep for 10 seconds:

package main
import "time"

func main() {
  // ...
  time.Sleep(10 * time.Second)
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Sleep for milliseconds

time.Millisecond can be used to sleep for X milliseconds:

package main
import "time"

func main() {
  // ...
  time.Sleep(50 * time.Millisecond)
  // ...
}
Enter fullscreen mode Exit fullscreen mode

You can also sleep for minutes or hours.

Top comments (0)