-1

I'm trying to write my own sleep function equivalent to time.Sleep using time.After in Go.

Here's the code. First attempt:

func Sleep(x int) {
  msg := make(chan int)
  msg := <- time.After(time.Second * x)
}

Second attempt:

func Sleep(x int) {
 time.After(time.Second * x)
}

Both return errors, can someone explain to me how to write a sleep function equivalent to time.Sleep using time.After and if possible when do I use channel?

icza
  • 389,944
  • 63
  • 907
  • 827
airsoftFreak
  • 1,450
  • 5
  • 34
  • 64
  • take a look at http://stackoverflow.com/questions/23582143/golang-using-timeouts-with-channels as well as http://stackoverflow.com/questions/16466320/is-there-a-way-to-do-repetitive-tasks-at-intervals-in-golang – Richard Chambers Aug 11 '15 at 12:48

1 Answers1

7

time.After() returns you a channel. And a value will be send on the channel after the specified duration.

So just receive a value from the returned channel, and the receive will block until the value is sent:

func Sleep(x int) {
    <-time.After(time.Second * time.Duration(x))
}

Your errors:

In your first example:

msg := <- time.After(time.Second * x)

msg is already declared, and so the Short variable declaration := cannot be used. Also the recieved value will be of type time.Time, so you can't even assign it to msg.

In your second example you need a type conversion as x is of type int and time.Second is of type time.Duration, and time.After() expects a value of type time.Duration.

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you so much icza, you safe me again. I have so much questions on golang. – airsoftFreak Aug 11 '15 at 13:13
  • I don't understand this part **<-time.After(time.Second * time.Duration(x))** is it receiving ? – airsoftFreak Aug 11 '15 at 13:16
  • @airsoftFreak `time.After()` returns a channel. And the `<-` is the [receive operator](https://golang.org/ref/spec#Receive_operator) applied on the return value of `time.After()`. – icza Aug 11 '15 at 13:19
  • Can someone explain how to use the Sleep(x int) function above? ```go Sleep(10)``` with a print statement after executes immediately so I know this isn't working for me. – Shawn Oct 20 '17 at 20:10
  • 1
    @Shawn 3 years later, here's your answer :P - because you used `go` in front of `Sleep`, it executed the sleep in a goroutine (in the background) and executed the print straight after. If you remove the `go` it should work just fine. – user9123 Dec 12 '20 at 16:13