Hokutosei Hokutosei - 11 months ago 47
Node.js Question

nodejs setTimeout equivalent in Golang

currently I'm studying, and I miss setTimeout from Nodejs in golang. I haven't read much yet, and I'm wondering if I could implement the same in go like an interval or a loopback

is there a way that i can write this from node to golang? I heard golang handles concurrency very well, and this might be some goroutines or else?

function main() {

//Do something

setTimeout(main, 3000)
console.log('Server is listening to 1337')

Thank you in advance!

//Go version

func main() {
for t := range time.Tick(3*time.Second) {
fmt.Printf("working %s \n", t)

//basically this will not execute..
fmt.Printf("will be called 1st")

Answer Source

The closest equivalent is the time.AfterFunc function:

import "time"

time.AfterFunc(3*time.Second, somefunction)

This will spawn a new goroutine and run the given function after the specified amount of time. There are other related functions in the package that may be of use:

  • time.After: this version will return a channel that will send a value after the given amount of time. This can be useful in combination with the select statement if you want a timeout while waiting on one or more channels.

  • time.Sleep: this version will simply block until the timer expires. In Go it is more common to write synchronous code and rely on the scheduler to switch to other goroutines, so sometimes simply blocking is the best solution.

There is also the time.Timer and time.Ticker types that can be used for less trivial cases where you may need to cancel the timer.