From 46171082002bb756222b05fe056480f76204198d Mon Sep 17 00:00:00 2001 From: "R. Aidan Campbell" Date: Mon, 28 Nov 2022 17:08:50 -0700 Subject: [PATCH] fix: example to clean up watchdog goroutine (#431) Fix the example to clean up watchdog goroutine after either the timeout or the VM completes. Co-authored-by: Steven Hartland --- README.markdown | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index 40584d3..5dfa643 100644 --- a/README.markdown +++ b/README.markdown @@ -236,12 +236,18 @@ func runUnsafe(unsafe string) { vm := otto.New() vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking + watchdogCleanup := make(chan struct{}) + defer close(watchdogCleanup) go func() { - time.Sleep(2 * time.Second) // Stop after two seconds - vm.Interrupt <- func() { - panic(halt) + select { + case <-time.After(2 * time.Second): // Stop after two seconds + vm.Interrupt <- func() { + panic(halt) + } + case <-watchdogCleanup: } + close(vm.Interrupt) }() vm.Run(unsafe) // Here be dragons (risky code)