Combine time.After with context.WithTimeout to create a cancellable operation that stops after a set duration.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
select {
case <-time.After(10 * time.Second):
fmt.Println("Timed out")
case <-ctx.Done():
fmt.Println("Context cancelled")
}
This pattern ensures the operation respects the timeout defined in the context while time.After provides a fallback timer.