Skip to content

Instantly share code, notes, and snippets.

@kitlabcode
Created April 13, 2023 22:04
Show Gist options
  • Select an option

  • Save kitlabcode/7649b0abef9a864440aa0d396a0e5fa3 to your computer and use it in GitHub Desktop.

Select an option

Save kitlabcode/7649b0abef9a864440aa0d396a0e5fa3 to your computer and use it in GitHub Desktop.
try function until
// You can edit this code!
// Click here and start typing.
package main
import (
"context"
"fmt"
"time"
)
func tryFunc(ctx context.Context, f func() bool) bool {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return false
case <-ticker.C:
if b := f(); b {
return b
}
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
i := 0
outcome := tryFunc(ctx, func() bool { i++; return i == 2 })
fmt.Println(outcome)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment