[Golang/GopherJS] setTimeout


JavaScript setTimeout equivalent in Go/GopherJS - time.AfterFunc.

Demo

Source code: time.AfterFunc is Go's setTimeout.

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>GopherJS setTimeout Demo</title>
</head>
<body>

<button id="btn" type="button">Click Me!</button>
<br><br>
<div id="info">Click button to start 3 second timer</div>

<script src="app.js"></script>
</body>
</html>
app.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"github.com/gopherjs/gopherjs/js"
	"time"
)

func main() {
	info := js.Global.Get("document").Call("getElementById", "info")
	button := js.Global.Get("document").Call("getElementById", "btn")

	button.Set("onclick", func(e *js.Object) {
		// time.AfterFunc is Go's setTimeout
		time.AfterFunc(3*time.Second, func() {
			info.Set("innerHTML", "time is up")
		})
	})
}

References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]GitHub - siongui/gopherjs-tooltip: Tooltip in Go. Compiled to JavaScript via GopherJS
[3]
[4]Are multiple time.After statements racing in "select" : golang