How to Use time.After and time.Tick in Go

Use time.After for single delays and time.NewTicker for repeated intervals to manage timing in Go programs effectively.

Use time.After for one-time delays and time.Tick for continuous intervals, but prefer time.NewTicker for production code to avoid goroutine leaks. time.After returns a channel that sends the current time once after the duration, while time.Tick returns a channel that sends the current time repeatedly at the interval.

package main

import (
	"fmt"
	"time"
)

func main() {
	// One-time delay
	fmt.Println("Waiting 2 seconds...")
	<-time.After(2 * time.Second)
	fmt.Println("Done waiting.")

	// Continuous interval (use NewTicker in production)
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()
	for range ticker.C {
		fmt.Println("Tick")
		time.Sleep(3 * time.Second) // Stop after 3 ticks
		break
	}
}