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") }
The setTimeout function is found in the Timers module of Node. js.
setTimeout() can be used to schedule code execution after a designated amount of milliseconds. This function is similar to window. setTimeout() from the browser JavaScript API, however a string of code cannot be passed to be executed.
setTimeout and setInterval are not actually included in javascript - let's understand this. Maybe you think setTimeout like this -: The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
Maximum delay value Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With