golang

How To Use time.Sleep() Function in Golang

The Golang programming language’s fundamental component functions are crucial to the creation of effective and scalable programs. Functions can increase code reusability and concurrency. One of the functions is time.Sleep() in Golang specifies the delay in script processing. We will learn about the time.Sleep() function of Golang in this article with examples.

What Is time.Sleep() Function in Golang

In Golang, a program’s execution can be paused for a set amount of time using the time.Sleep() function. The amount of time to suspend the running of the program is the single argument that the time.Sleep() function accepts, below is the syntax for it:

time.Sleep(d * time-unit)

Where d is the time duration and time-unit can be seconds, or milliseconds.

How to use time.Sleep() function in Golang

The time.Sleep() is employed to make delays in the execution process of the Golang program. It is necessarily used to limit the rate of a certain amount of time in program exceptions. Now let’s see the examples of time.Sleep() function in Golang programming.

Example 1: Golang time.Sleep() Function (Seconds)

The following Golang code suspends the program execution for three seconds:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Hello")
    fmt.Println("Execution paused for three seconds")
    time.Sleep(3 * time.Second)
    fmt.Println("Execution resumed")
    fmt.Println("Welcome to Linux hint")
}

In the main function using fmt.Println() function strings are displayed. After that time.Sleep() function is called with the value of 3 in seconds. After 3 seconds the following instructions will execute displaying the respective strings.

Example 2: Golang time.Sleep() Function (Milliseconds)

The following example application utilizes a time.Sleep() function to stop the execution for a given amount of time, measured in three thousand milliseconds:

package main

import (
    "fmt"
    "time"
)

funcmain() {
    fmt.Println("Hello")
    fmt.Println("Execution paused for 3000milliseconds")
    time.Sleep(3000 * time.Millisecond)
    fmt.Println("Execution resumed")
    fmt.Println("Welcome to Linuxhint")
}

When the main function execution started, it printed Hello using fmt.Println() then, this example prints Execution paused for 3000 milliseconds to the console. Once the execution is resumed it prints the message Execution resumed and then executes the next instruction.

Conclusion

The time.Sleep() function is often employed in Go scripts to add pauses in the code execution. This article explained the time.Sleep() function with the help of examples that makes some pauses in seconds and milliseconds.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.