To pause the execution of a current program in Go, delay code execution, and wait for a specified period of time, you just need to use the Sleep() function defined in the time package. As an argument, this function takes a variable of type time.
Sleeping, or waiting in Go, is part of the time package. It's a very simple process, all you need to do is specify the duration to sleep for, which in this case is a number followed by it's unit, so 2*time. Second means 2 seconds. This will sleep the current goroutine so other go routines will continue to run.
You can pause the program for an arbitrarily long time by using time.Sleep()
. For example:
package main
import ( "fmt"
"time"
)
func main() {
fmt.Println("Hello world!")
duration := time.Second
time.Sleep(duration)
}
To increase the duration arbitrarily you can do:
duration := time.Duration(10)*time.Second // Pause for 10 seconds
EDIT: Since the OP added additional constraints to the question the answer above no longer fits the bill. You can pause until the Enter key is pressed by creating a new buffer reader which waits to read the newline (\n
) character.
package main
import ( "fmt"
"bufio"
"os"
)
func main() {
fmt.Println("Hello world!")
fmt.Print("Press 'Enter' to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
package main
import "fmt"
func main() {
fmt.Println("Press the Enter Key to terminate the console screen!")
fmt.Scanln() // wait for Enter Key
}
The easiest another way with minimal imports use this 2 lines :
var input string
fmt.Scanln(&input)
Adding this line at the end of the program, will pause the screen until user press the Enter Key, for example:
package main
import "fmt"
func main() {
fmt.Println("Press the Enter Key to terminate the console screen!")
var input string
fmt.Scanln(&input)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With