How to Use Sleep in Go: Simple Guide with Examples
In Go, you use
time.Sleep to pause the program for a specific duration. Import the time package and call time.Sleep(duration), where duration is a time interval like time.Second.Syntax
The time.Sleep function pauses the current goroutine for the specified duration.
time.Sleep(d time.Duration): Pauses execution fordduration.time.Duration: Represents time intervals, e.g.,time.Second,time.Millisecond.
go
time.Sleep(d time.Duration)
Example
This example shows how to pause the program for 2 seconds using time.Sleep. It prints a message, waits, then prints another message.
go
package main import ( "fmt" "time" ) func main() { fmt.Println("Start sleeping...") time.Sleep(2 * time.Second) fmt.Println("Awake after 2 seconds") }
Output
Start sleeping...
Awake after 2 seconds
Common Pitfalls
Common mistakes when using time.Sleep include:
- Forgetting to import the
timepackage. - Passing an integer without a time unit (e.g.,
time.Sleep(2)is invalid). - Using
time.Sleepin the main goroutine without understanding it blocks only that goroutine.
go
package main import ( "fmt" "time" ) func main() { // Wrong: missing time unit // time.Sleep(2) // This will cause a compile error // Correct usage time.Sleep(2 * time.Second) fmt.Println("Slept correctly") }
Output
Slept correctly
Quick Reference
| Function | Description | Example |
|---|---|---|
| time.Sleep | Pauses current goroutine for given duration | time.Sleep(500 * time.Millisecond) |
| time.Second | Represents one second duration | time.Sleep(3 * time.Second) |
| time.Millisecond | Represents one millisecond duration | time.Sleep(100 * time.Millisecond) |
Key Takeaways
Use time.Sleep with a time.Duration value to pause execution in Go.
Always import the time package before using time.Sleep.
Specify the duration with units like time.Second or time.Millisecond.
time.Sleep only pauses the current goroutine, not the entire program.
Avoid passing plain integers without time units to time.Sleep.