Monday, February 2, 2015

A Simple Golang Example - Sleep Function

Golang code is organised and reused using packages. The package time provides functionality for measuring and displaying time. Here, I've created a simple example to understand the Sleep() function of time package.

Like many other languages, Sleep() function as the name suggests pauses the current execution for the duration specified in the function. See the below image, line# 12, where Sleep() is used to introduce a delay of 1.3 Seconds between the print of every successive number in multiplication table of 2.

You can check the live example here at Go Playground.

You can change line# 12 and can write any of the following to get the same duration of delay:

So instead of

time.Sleep(time.Millisecond * 1300) 

We can write this:

time.Sleep(time.Microsecond * 1300 * 1000)

Or this

time.Sleep(time.Nanosecond * 1300 * 1000 * 1000)


You can provide the duration in Second also but it should not be in decimals.
time.Sleep(time.Second * 1)   

The above call provide a pause of 1 second. But if you replace this with the following code
time.Sleep(time.Second * 1.3) 


It won't work. You'll get a runtime error. That's where the Millisecond comes to your rescue, as to pause for 1.3 seconds you can choose 1.3 * 1000 i.e. 1300 milliseconds. You can provide duration values in Minutes & Hour as well.

Please share your views for improvement.