github.com/goplusjs/gopherjs@v1.2.6-0.20211206034512-f187917453b8/compiler/natives/src/time/time.go (about) 1 // +build js 2 3 package time 4 5 import ( 6 "github.com/gopherjs/gopherjs/js" 7 ) 8 9 // Make sure time.Unix func and time.Time struct it returns are always included with this package (despite DCE), 10 // because they're needed for internalization/externalization of time.Time/Date. See issue https://github.com/gopherjs/gopherjs/issues/279. 11 func init() { 12 // avoid dead code elimination 13 var _ Time = Unix(0, 0) 14 } 15 16 func runtimeNano() int64 { 17 return js.Global.Get("Date").New().Call("getTime").Int64() * int64(Millisecond) 18 } 19 20 func now() (sec int64, nsec int32, mono int64) { 21 n := runtimeNano() 22 return n / int64(Second), int32(n % int64(Second)), n 23 } 24 25 func Sleep(d Duration) { 26 c := make(chan struct{}) 27 js.Global.Call("$setTimeout", js.InternalObject(func() { close(c) }), int(d/Millisecond)) 28 <-c 29 } 30 31 func startTimer(t *runtimeTimer) { 32 t.active = true 33 diff := (t.when - runtimeNano()) / int64(Millisecond) 34 if diff > 1<<31-1 { // math.MaxInt32 35 return 36 } 37 if diff < 0 { 38 diff = 0 39 } 40 t.timeout = js.Global.Call("$setTimeout", js.InternalObject(func() { 41 t.active = false 42 if t.period != 0 { 43 t.when += t.period 44 startTimer(t) 45 } 46 go t.f(t.arg, 0) 47 }), diff+1) 48 } 49 50 func stopTimer(t *runtimeTimer) bool { 51 js.Global.Call("clearTimeout", t.timeout) 52 wasActive := t.active 53 t.active = false 54 return wasActive 55 } 56 57 // indexByte is copied from strings package to avoid importing it (since the real time package doesn't). 58 func indexByte(s string, c byte) int { 59 return js.InternalObject(s).Call("indexOf", js.Global.Get("String").Call("fromCharCode", c)).Int() 60 }