AlgoMaster Logo

context.WithTimeout

High Priority13 min readUpdated June 6, 2026

context.WithTimeout is the version of WithCancel to use when "cancel when I say so" becomes "cancel if this takes longer than X". It wraps a parent context and starts a timer; when the timer fires, the new context is cancelled automatically and ctx.Err() reports context.DeadlineExceeded. This chapter covers how that timer behaves, why you still need defer cancel(), and how to race a slow operation against the timeout using select.

Premium Content

Subscribe to unlock full access to this content and more premium articles.