65 lines
1.0 KiB
Go
65 lines
1.0 KiB
Go
package js
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/dop251/goja"
|
|
)
|
|
|
|
type interval struct {
|
|
goja.Callable
|
|
this goja.Value
|
|
args []goja.Value
|
|
cancelled bool
|
|
ticker *time.Ticker
|
|
stopChan chan int
|
|
}
|
|
|
|
func (s *Simulator) setInterval(call goja.FunctionCall) goja.Value {
|
|
fn, ok := goja.AssertFunction(call.Argument(0))
|
|
if !ok {
|
|
return nil
|
|
}
|
|
delay := call.Argument(1).ToInteger()
|
|
var args []goja.Value
|
|
if len(call.Arguments) > 2 {
|
|
args = call.Arguments[2:]
|
|
}
|
|
|
|
i := &interval{
|
|
Callable: fn,
|
|
args: args,
|
|
ticker: time.NewTicker(time.Duration(delay) * time.Millisecond),
|
|
stopChan: make(chan int),
|
|
}
|
|
|
|
s.intervals = append(s.intervals, i)
|
|
s.intervalsWg.Add(1)
|
|
go func() {
|
|
defer s.intervalsWg.Done()
|
|
for {
|
|
select {
|
|
case <-i.stopChan:
|
|
i.ticker.Stop()
|
|
return
|
|
case <-i.ticker.C:
|
|
if i.cancelled {
|
|
i.ticker.Stop()
|
|
return
|
|
}
|
|
|
|
fn := func() {
|
|
_, err := i.Callable(i.this, i.args...)
|
|
if err != nil {
|
|
s.m.Error(err)
|
|
}
|
|
}
|
|
|
|
s.dispatchC <- fn
|
|
}
|
|
}
|
|
}()
|
|
|
|
return s.vm.ToValue(i)
|
|
}
|