Golang time.Sleep() function is “used to stop the execution of the current go-routine for a specified amount of time“.
Syntax
func Sleep(dur Duration)
Parameters
The dur is the duration of time in seconds to sleep.
Return value
The time.Sleep() function pauses the latest go-routine for the stated duration and returns the operation’s output after sleep.
Important note
The time.Sleep() function blocks the current Goroutine and will not allow any other Goroutines to run while it’s sleeping. This can induce a performance issue if the Goroutine is sleeping for a long time.
Example 1
Write a Golang program that will put the program to sleep for 5 seconds.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Started")
time.Sleep(5 * time.Second)
fmt.Println("Finished")
}
Output
Started
// 5 seconds sleep
Finished
Example 2
Here’s another Go program that demonstrates the use of channels, goroutines, and the select statement for handling timeouts with different channels:
package main
import (
"fmt"
"time"
)
func main() {
channel1 := make(chan string, 2)
channel2 := make(chan string, 2)
go func() {
time.Sleep(2 * time.Second)
channel1 <- "message from channel 1"
}()
go func() {
time.Sleep(4 * time.Second)
channel2 <- "message from channel 2"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-channel1:
fmt.Println("Received:", msg1)
case msg2 := <-channel2:
fmt.Println("Received:", msg2)
case <-time.After(3 * time.Second):
fmt.Println("Timeout occurred")
}
}
}
Output
Received: message from channel 1
Received: message from channel 2
That’s it.
Similar Posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.