Skip to content

Go Channel Operation Timeout — Complete Guide

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Channel Operation Timeout. We cover key concepts, practical examples, and best practices.

Channel timeout -- Add timeouts to channel operations using select with time.After to prevent indefinite blocking.

The Problem

Reading from or writing to a channel can block forever. Use select with time.After to implement timeouts on channel operations.

Wrong

val := <-ch // Blocks forever if no sender!

Output:

// Goroutine blocks indefinitely if nothing sends on ch
select {
case val := <-ch:
    fmt.Println("Got:", val)
case <-time.After(5 * time.Second):
    fmt.Println("Timeout waiting for value")
}

Output:

Timeout waiting for value
// Returned control after 5 seconds

Prevention

  • Use time.After in select for channel timeouts
  • time.After creates a timer that fires once
  • Timer leaks if select completes before timeout
  • Use time.NewTimer + Stop() to prevent leaks
  • Combine with context for more control

Common Mistakes with channel timeout

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does time.After leak?**

Yes, if select exits before timeout fires. Use time.NewTimer and timer.Stop().

How to stop the timer early?

timer.Stop() returns false if already fired.

Can I use time.Tick for repeated timeouts?

Use time.NewTicker instead. time.Tick leaks.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro