Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add pause to a Go program?

Tags:

go

People also ask

How do I pause the go program?

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.

How to make golang Sleep?

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)
}