What is the time.sleep method in Go?
Overview
In developing an application, we would want to have time in between the code blocks, where we allow every other code to run without initiating a new code execution. This can be done using the. time.sleep() method.
Syntax
time.Sleep(d * timeunit)
Parameter
The sleep method takes three parameters.
d: This represents the duration.*: This represents the multiplier last.timeunit: This can be in seconds, milliseconds, and so on.
Example
package mainimport ("fmt""time")// Main functionfunc main() {// Calling Sleep methodtime.Sleep(8 * time.Second)// Printed after sleep is overfmt.Println("Rest is good")}
Explanation
-
Line 5-6: We import the needed packages. That is the
fmtpackage that we use to display output. We also import thetimeobject, which we use to execute oursleep()function. -
Line 14: We call the
time.Sleep(8 * time.Second)to delay the code execution by 8 seconds. -
Line 17: We print a text after the 8 seconds sleep delay.