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