# Code Snippet

## Do anything timeout

```go
func DoTimeout(ctx context.Context, timeout time.Duration, f func() (interface{}, error)) (interface{}, error) {
	ctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()

	var resp interface{}
	var err error
	var lock sync.Mutex

	done := make(chan struct{})
	panicChain := make(chan interface{}, 1)

	go func() {
		defer func() {
			if p := recover(); p != nil {
				panicChain <- p
			}
		}()

		r, e := f()

		lock.Lock()
		defer lock.Unlock()
		resp = r
		err = e

		close(done)
	}()

	select {
	case <-done:
		lock.Lock()
		defer lock.Unlock()
		return resp, err
	case p := <-panicChain:
		return nil, fmt.Errorf("call function panic: %v", p)
	case <-ctx.Done():
		return nil, ctx.Err()
	}
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yunzhao.gitbook.io/notes/go/code-snippet.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
