How to use time.Sleep in Go (Golang) to pause execution
Table of Contents
The time.Sleep function pauses the current goroutine for a specific duration. It is the simplest way to delay execution in Go and is built into the standard time package. ⏱️
What is time.Sleep? #
time.Sleep(d time.Duration) blocks the current goroutine for d. The duration is expressed as a number multiplied by a time unit, like 500*time.Millisecond or 2*time.Second.
Common units:
time.Nanosecondtime.Microsecondtime.Millisecondtime.Secondtime.Minutetime.Hour
When to use time.Sleep #
Use it for short, controlled delays such as:
- Simulating network latency in a demo
- Spacing out retries with a fixed delay
- Pacing log output in CLI tools
How to pause execution with time.Sleep #
This full program prints a message, sleeps for 3 seconds, and continues:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("before Sleep()")
time.Sleep(3 * time.Second)
fmt.Println("waking up after Sleep()")
}
Common mistakes #
❌ Using plain integers without a unit:
time.Sleep(3) // sleeps for 3 nanoseconds, not 3 seconds
✅ Always multiply by a time unit:
time.Sleep(3 * time.Second)
❌ Using time.Sleep to coordinate goroutines:
time.Sleep(100 * time.Millisecond) // unreliable synchronization
✅ Use channels, sync.WaitGroup, or context for coordination.
Best practices #
- Keep delays explicit and small; prefer
time.Durationvariables for clarity. - If you need timeouts, use
contextortime.Timerinstead of hard sleeps. - Document why the delay exists to avoid accidental removal. ✅
Related topics #
- Measure execution time in Go - time code blocks reliably
- Range over a ticker in Go - periodic work without manual sleeps
- Handle context deadline exceeded - timeouts with context
- HTTP client timeout in Go - timeouts for requests
- Convert time to string in Go - formatting time values
Tested with Go 1.25+ | Last verified: December 2025 🎉