What is time.After() Function in Golang

The time.After() is a built-in Golang function that creates a channel to send the current time after a specified duration has elapsed. This function is often used for implementing timeouts or performing an action after a certain delay.

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

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

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