diff --git a/d2cli/main.go b/d2cli/main.go index 774a873ace..dedba22b09 100644 --- a/d2cli/main.go +++ b/d2cli/main.go @@ -291,17 +291,16 @@ func compile(ctx context.Context, ms *xmain.State, plugin d2plugin.Plugin, sketc opts.FontFamily = go2.Pointer(d2fonts.HandDrawn) } - kill := background.DoEveryX(func() { + cancel := background.Repeat(func() { ms.Log.Info.Printf("compiling & running layout algorithms...") }, time.Second*5) - - defer kill() + defer cancel() diagram, g, err := d2lib.Compile(ctx, string(input), opts) if err != nil { return nil, false, err } - kill() + cancel() pluginInfo, err := plugin.Info(ctx) if err != nil { diff --git a/lib/background/background.go b/lib/background/background.go index 62ca734392..ad16a16fd1 100644 --- a/lib/background/background.go +++ b/lib/background/background.go @@ -2,27 +2,27 @@ package background import "time" -func DoEveryX(do func(), x time.Duration) (kill func()) { - stopped := false - t := time.NewTicker(x) - stop := make(chan struct{}) +func Repeat(do func(), interval time.Duration) (cancel func()) { + t := time.NewTicker(interval) + done := make(chan struct{}) go func() { + defer t.Stop() for { select { case <-t.C: do() - case <-stop: + case <-done: return } } }() + stopped := false return func() { if !stopped { stopped = true - t.Stop() - close(stop) + close(done) } } } diff --git a/lib/png/png.go b/lib/png/png.go index 58fa9d4b1c..8f89c0b206 100644 --- a/lib/png/png.go +++ b/lib/png/png.go @@ -84,11 +84,10 @@ var genPNGScript string const pngPrefix = "data:image/png;base64," func ConvertSVG(ms *xmain.State, page playwright.Page, svg []byte) ([]byte, error) { - kill := background.DoEveryX(func() { + cancel := background.Repeat(func() { ms.Log.Info.Printf("converting to PNG...") }, time.Second*5) - - defer kill() + defer cancel() encodedSVG := base64.StdEncoding.EncodeToString(svg) pngInterface, err := page.Evaluate(genPNGScript, "data:image/svg+xml;charset=utf-8;base64,"+encodedSVG)