Reputation: 325
I am wondering how I can skip to the end of this function after 3_000 milliseconds but without any other printed message on screen or calling other functions or sending further messages.
defmodule ExampleModule do
def main do
Process.send_after(self(), :hello, 2_000)
send self(), :hello_again
next()
end
def next do
receive do
:hello -> IO.puts("Received hello")
:hello_again -> IO.puts("Received hello_again")
after 3_000 -> <SKIP to the very end without recursion>
end
next()
end
end
Upvotes: 0
Views: 105
Reputation: 222448
There is no construct like goto
or return
in Elixir. Here are two ways you can solve this:
Explicitly call next()
in the branches you want to continue recursing:
def next do
receive do
:hello ->
IO.puts("Received hello")
next()
:hello_again ->
IO.puts("Received hello_again")
next()
after 3_000 ->
:ok
end
end
Store the value of the receive expression and call next()
based on that:
def next do
continue = receive do
:hello ->
IO.puts("Received hello")
true
:hello_again ->
IO.puts("Received hello_again")
true
after 3_000 ->
false
end
if continue, do: next()
end
Upvotes: 2