首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Golang中,nodejs setTimeout的等价物是什么?

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

Stack Overflow用户
提问于 2014-06-06 09:23:24
回答 4查看 10K关注 0票数 23

我现在正在学习,我很怀念来自golang的Nodejs的setTimeout。我还没有读到太多,我想知道我是否可以在go中实现同样的东西,比如一个间隔或一个回环。

有没有办法把这段代码从node写到golang?我听说golang很好地处理并发,这可能是一些goroutines或其他?

代码语言:javascript
复制
//Nodejs
function main() {

 //Do something

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

提前谢谢你!

代码语言:javascript
复制
//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")
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-06-06 10:09:08

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

代码语言:javascript
复制
import "time"

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

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

  • time.After:此版本将返回一个通道,该通道将在给定的时间量之后发送一个值。如果您想在等待一个或多个channels.
  • time.Sleep:时超时,这与select语句结合使用会很有用,此版本将简单地阻塞,直到计时器超时。在Go中,更常见的是编写同步代码并依靠调度程序切换到其他goroutine,所以有时简单地阻塞是最好的解决方案。

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

票数 37
EN

Stack Overflow用户

发布于 2016-09-08 20:37:16

另一种解决方案可以是实现

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

代码语言:javascript
复制
go func() {
  time.Sleep(time.Second * 3)
  // your code here
}()
票数 1
EN

Stack Overflow用户

发布于 2018-03-08 04:47:19

website提供了一个涉及通道和select函数的有趣的超时示例和解释。

代码语言:javascript
复制
// _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上运行它

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24072767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档