How to Use the time.After() Function in Golang

Golang time.After() function is “used to wait for the duration to elapse and then sends the current time on the returned channel”.

Syntax

func After(d Duration) <-chan Time

Parameters

Sleep pauses the current goroutine for at least the duration d.

Return value

It waits for the stated time and then displays a timeout.

Example 1: How to Use time.After() function

package main

import (
  "fmt"
  "time"
)

func main() {
  select {
    case <-time.After(3 * time.Second):
    fmt.Println("3 seconds have passed")
 }
}

Output

3 seconds have passed

In this example, we used the select statement to wait for the time.After() channel to send a value. It blocked the select statement and printed “3 seconds have passed” after the 3-second duration had elapsed.

Example 2: Use a goroutine with time.After() Method

package main

import (
  "fmt"
  "time"
)

func main() {
  messageChan := make(chan string)

  go func() {
    time.Sleep(3 * time.Second)
    messageChan <- "Hello from goroutine!"
  }()

  select {
   case msg := <-messageChan:
     fmt.Println("Received message:", msg)
   case <-time.After(5 * time.Second):
    fmt.Println("Timeout: No message received within 3 seconds")
  }
}

Output

Received message: Hello from goroutine!

In this example, we created a goroutine that sleeps for 3 seconds and then sends a message to the messageChan channel.

We used a select statement to wait for either a message from the messageChan or a timeout signal from the time.After() function.

If a message is received within 3 seconds, it will be printed. If it sleeps for 5 seconds before sending the message, the time.After() channel will trigger first and print “Timeout: No message received within 3 seconds”.

That’s it.

Leave a Comment