educative.io

Confusion in Getting order using sleep

How does this line in following function assures order of output?

time.Sleep(50 * time.Millisecond)
func printTable(n int, wg *sync.WaitGroup) {  for i := 1; i <= 12; i++ {    fmt.Printf("%d x %d = %d\n", i, n, n*i)    time.Sleep(50 * time.Millisecond)  }  wg.Done()}

Hi @Tejas1,

The line time.Sleep(50 * time.Millisecond) in printTable function introduces a delay of 50 milliseconds between each iteration of the loop. This sleep is intended to slow down the printing process, creating a pause between each line of the multiplication table.

This sleep helps in ensuring that the output lines are printed with a delay, making it easier to observe the output in an ordered manner. Without this delay, the lines might get printed quickly, and the output could become harder to read, especially when there are multiple goroutines printing simultaneously.

In summary, the time.Sleep function introduces a pause to control the rate at which the lines are printed, helping to maintain the order and readability of the output.

I hope this helps! Happy Learning :slight_smile:

Understood. Thanks for the reply

1 Like