Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the nodejs setTimeout equivalent in Golang?

Tags:

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") } 
like image 447
Hokutosei Avatar asked Jun 06 '14 01:06

Hokutosei


People also ask

Does node js have setTimeout?

The setTimeout function is found in the Timers module of Node. js.

What is setTimeout Nodejs?

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.

Is setTimeout part of JavaScript?

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.

Is there a limit for setTimeout?

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.


1 Answers

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.

like image 106
James Henstridge Avatar answered Sep 29 '22 19:09

James Henstridge