setTimeout method in Go


setTimeout method in JavaScript is used to run a function after waiting a specific length of time. The equivalent in Go is time.AfterFunc method in Go standard library. This post show you how to use time.AfterFunc in Go and compile the Go code to run on browsers via GopherJS. Note that if you are not doing frontend programming, you can still use time.AfterFunc on backend servers or local machines.

JavaScript setTimeout = Go time.AfterFunc

JavaScript

setTimeout(function() {
  console.log("3 seconds timeout");
}, 3000);

Go or GopherJS

The above code in Go/GopherJS is as follows:

import (
      "time"
)

func main() {
      time.AfterFunc(3*time.Second, func() {
              println("3 seconds timeout")
      })
}

Run Code on GopherJS Playground

Note that you do not have to import GopherJS package in your Go code. GopherJS will compile time.AfterFunc code to corresponding JavaScript code for you. You feel like writing a local Go program and do not even have to know about setTimeout method! The code here can be used both on front and backend!

The full code example of this post is on my GitHub. For more complicated example, see my another post [3].


References:

[1][JavaScript] Type Text Effect
[2][JavaScript] Typing Text Effect
[3][Golang/GopherJS] setTimeout