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

时间:2014-06-06 01:23:24

标签: node.js concurrency go settimeout

我目前正在学习,我想念golang中的Nodejs setTimeout。我还没读过多少内容,而且我想知道我是否可以像间隔或环回一样实现相同的功能。

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

//Nodejs
function main() {

 //Do something

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

提前谢谢!

//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")
}

3 个答案:

答案 0 :(得分:23)

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

import "time"

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

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

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

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

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

答案 1 :(得分:1)

另一个解决方案可能是实现

立即调用函数表达式(IIFE)函数如:

go func() {
  time.Sleep(time.Second * 3)
  // your code here
}()

答案 2 :(得分:0)

这个website提供了一个有趣的例子和解释涉及频道和选择功能的超时。

// _Timeouts_ are important for programs that connect to
// external resources or that otherwise need to bound
// execution time. Implementing timeouts in Go is easy and
// elegant thanks to channels and `select`.

package main

import "time"
import "fmt"

func main() {

    // For our example, suppose we're executing an external
    // call that returns its result on a channel `c1`
    // after 2s.
    c1 := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second)
        c1 <- "result 1"
    }()

    // Here's the `select` implementing a timeout.
    // `res := <-c1` awaits the result and `<-Time.After`
    // awaits a value to be sent after the timeout of
    // 1s. Since `select` proceeds with the first
    // receive that's ready, we'll take the timeout case
    // if the operation takes more than the allowed 1s.
    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(1 * time.Second):
        fmt.Println("timeout 1")
    }

    // If we allow a longer timeout of 3s, then the receive
    // from `c2` will succeed and we'll print the result.
    c2 := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second)
        c2 <- "result 2"
    }()
    select {
    case res := <-c2:
        fmt.Println(res)
    case <-time.After(3 * time.Second):
        fmt.Println("timeout 2")
    }
}

您也可以在Go Playground

上运行它