What is the nodejs setTimeout equivalent in Golang?

huangapple go评论97阅读模式
英文:

What is the nodejs setTimeout equivalent in Golang?

问题

我目前正在学习,我想念Node.js中的setTimeout函数,想知道在Go语言中是否可以实现类似的定时器或循环。

在Go语言中,你可以使用goroutine和定时器来实现类似的功能。下面是将Node.js中的代码转换为Go语言的示例:

package main

import (
	"fmt"
	"time"
)

func main() {
	go func() {
		for {
			// Do something

			time.Sleep(3 * time.Second)
			fmt.Println("Server is listening to 1337")
		}
	}()

	// 主goroutine可以继续执行其他操作
	fmt.Println("Main goroutine is running")

	// 防止程序退出
	select {}
}

这段代码使用了匿名函数和goroutine来模拟Node.js中的setTimeout函数。通过使用time.Sleep函数来实现延迟执行,并在每次延迟结束后打印消息。

希望对你有帮助!

英文:

I am currently 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?

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

答案1

得分: 43

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

import "time"

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

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

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

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

还有time.Timertime.Ticker类型,可用于较为复杂的情况,例如可能需要取消计时器的情况。

英文:

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.

答案2

得分: 4

这个网站提供了一个有趣的例子和关于使用通道和select函数实现超时的解释。

// 对于连接外部资源或需要限制执行时间的程序来说,超时非常重要。在Go中,通过通道和`select`实现超时非常简单和优雅。

package main

import "time"
import "fmt"

func main() {

    // 举个例子,假设我们执行一个外部调用,并在2秒后将结果放入通道`c1`中。
    c1 := make(chan string, 1)
    go func() {
        time.Sleep(2 * time.Second)
        c1 <- "result 1"
    }()

    // 这里使用`select`实现超时。
    // `res := <-c1`等待结果,`<-Time.After`等待1秒后发送一个值。
    // 由于`select`会选择第一个准备好的接收操作,如果操作超过允许的1秒,我们将进入超时的情况。
    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(1 * time.Second):
        fmt.Println("timeout 1")
    }

    // 如果我们允许更长的超时时间3秒,那么从`c2`接收将成功,并打印结果。
    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上运行它。

英文:

This website provides an interesting example and explanation of timeouts involving channels and the select function.

// _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 &quot;time&quot;
import &quot;fmt&quot;

func main() {

    // For our example, suppose we&#39;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 &lt;- &quot;result 1&quot;
    }()

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

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

You can also run it on the Go Playground

答案3

得分: 1

另一种解决方案可以是实现一个立即调用的函数表达式(Immediately-Invoked Function Expression,IIFE),如下所示:

go func() {
  time.Sleep(time.Second * 3)
  // 在这里编写你的代码
}()
英文:

another solution could be to implement an

Immediately-Invoked Function Expression (IIFE) function like:

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

答案4

得分: 1

你可以使用sleep函数来实现这个功能,并设置你需要的延迟时间。

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("First")
	time.Sleep(5 * time.Second)
	fmt.Println("second")
}

这段代码会先打印出"First",然后暂停5秒钟,最后再打印出"second"。

英文:

you can do this by using sleep function
and give your duration you need

package main

import (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	fmt.Println(&quot;First&quot;)
	time.Sleep(5 * time.Second)
	fmt.Println(&quot;second&quot;)
}

huangapple
  • 本文由 发表于 2014年6月6日 09:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/24072767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定