What is the time.sleep method in Go?

Overview

In developing an application, we would want to have time in between the code blocks, where we allow every other code to run without initiating a new code execution. This can be done using the. time.sleep() method.

Syntax

time.Sleep(d * timeunit)

Parameter

The sleep method takes three parameters.

  • d: This represents the duration.
  • *: This represents the multiplier last.
  • timeunit: This can be in seconds, milliseconds, and so on.

Example

package main
import (
"fmt"
"time"
)
// Main function
func main() {
// Calling Sleep method
time.Sleep(8 * time.Second)
// Printed after sleep is over
fmt.Println("Rest is good")
}

Explanation

  • Line 5-6: We import the needed packages. That is the fmt package that we use to display output. We also import the time object, which we use to execute our sleep() function.

  • Line 14: We call the time.Sleep(8 * time.Second) to delay the code execution by 8 seconds.

  • Line 17: We print a text after the 8 seconds sleep delay.

Free Resources