Skip to content

time: Better docs for time.After #70821

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
cserban-plenty opened this issue Dec 13, 2024 · 2 comments
Closed

time: Better docs for time.After #70821

cserban-plenty opened this issue Dec 13, 2024 · 2 comments
Labels
Documentation Issues describing a change to documentation.

Comments

@cserban-plenty
Copy link

Go version

go1.23.1 darwin/arm64

Output of go env in your module/workspace:

Not Needed

What did you do?

package main

import (
	"fmt"
	"time"
)

func main() {
	wait := func() {
		ticker := time.NewTicker(time.Second)
		defer ticker.Stop()

		for {
			select {
			case <-ticker.C:
				fmt.Println("Tick")
			case <-time.After(time.Second * 5):
				fmt.Println("Done")
				return
			}
		}
	}

	wait()
}

What did you see happen?

time.After never gets triggered, for good reasons, it gets reset every iteration when selected. The docs could do better here.

What did you expect to see?

The example in docs looks like:

package main

import (
	"fmt"
	"time"
)

var c chan int

func handle(int) {}

func main() {
	select {
	case m := <-c:
		handle(m)
	case <-time.After(10 * time.Second):
		fmt.Println("timed out")
	}
}

And given that most of the time select is used inside a for loop, one could do so without thinking more about it, which can have side effects because in this case we'd create a new timer each iteration when the case is selected.

I know the docs at some point say that time.After is a shortcut to time.NewTimer(d).C but it also need a caution note that says it has to stay outside of a for loop.

@gopherbot gopherbot added the Documentation Issues describing a change to documentation. label Dec 13, 2024
@gabyhelp
Copy link

Related Issues

Related Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@seankhliao
Copy link
Member

it's quite a common pattern to use it in a for loop, and it's correct when the other select targets may be longer than the timeout. putting your per operation timeout outside the loop world be wrong if your operation takes any non trivial amount of time.

I don't see anything that should change here.

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Dec 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Documentation Issues describing a change to documentation.
Projects
None yet
Development

No branches or pull requests

4 participants