Replace After With Ticker In Loops
Swap time.After for one reusable Ticker inside polling loops so per-iteration timers stop piling up before they fire.
Code
package main
import (
"fmt"
"time"
)
func main() {
deadlines := make(chan string, 3)
go func() {
for i := 1; i <= 3; i++ {
deadlines <- fmt.Sprintf("task-%d done", i)
time.Sleep(20 * time.Millisecond)
}
}()
// 每轮 time.After 会新建一个定时器,未触发的要等到期才回收
// 循环里改用单个 Ticker:复用同一个通道,Stop 一次清理
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for i := 0; i < 3; i++ {
select {
case result := <-deadlines:
fmt.Println(result)
case <-ticker.C:
fmt.Println("tick: still waiting")
}
}
}How it works
Replace After With Ticker In Loops comes down to the function main.
A single loop drives the file — for i := 1; i <= 3; i++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func main()
Running the file prints labeled results such as tick: still waiting — each operation’s effect is visible in the output.
Key statements
deadlines <- fmt.Sprintf("task-%d done", i)
deadlines := make(chan string, 3)
defer ticker.Stop()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Replace After With Ticker In Loops print when run?
- Running the file directly is enough — expect labeled output lines such as `tick: still waiting`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.