Golang中的nodejs setTimeout等价物是什么?

Hok*_*sei 18 concurrency go settimeout node.js

我正在学习,我想念setTimeoutGolang的Nodejs.我还没有读过多少,我想知道我是否可以像间隔或环回一样实现相同的功能.

有没有办法可以将它从节点写入golang?我听说golang处理并发很好,这可能是一些goroutines或者其他?

//Nodejs
function main() {

 //Do something

 setTimeout(main, 3000)
 console.log('Server is listening to 1337')
}
Run Code Online (Sandbox Code Playgroud)

先感谢您!

//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")
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*dge 25

最接近的等价物是time.AfterFunc函数:

import "time"

...
time.AfterFunc(3*time.Second, somefunction)
Run Code Online (Sandbox Code Playgroud)

这将生成一个新的goroutine并在指定的时间后运行给定的函数.包中还有其他相关功能可能有用:

  • time.After:此版本将返回一个通道,该通道将在给定的时间后发送一个值.select如果您在等待一个或多个通道时想要超时,这可以与语句结合使用.

  • time.Sleep:这个版本只会阻塞,直到计时器到期.在Go中,更常见的是编写同步代码并依赖调度程序切换到其他goroutine,因此有时简单的阻塞是最佳解决方案.

还有一些time.Timertime.Ticker类型可用于您可能需要取消计时器的不太重要的情况.