How to slow down server response time for testing

I’m currently developing a frontend with React and would like to simulate slow response time with my Phoenix server. I’d like to implement some progress bars and spin wheels, but the server is way to fast to see them during testing…

How can this be done?

Maybe add a :timer.sleep(1000) (1 second in milliseconds) to your controller. Or write a plug which adds that and add it your your endpoint or route.

defmodule MyApp.Plugs.SlowResp do
  @moduledoc "Slows down responses to incoming requests"
  @behaviour Plug  

  # NOTE init is called during compilation
  def init(opts) do
    opts[:sleep] || raise("need :sleep option set for #{__MODULE__}")
    is_integer(opts[:sleep]) || raise(":sleep option for #{__MODULE__} needs to be an integer")
    opts
  end

  # and this is called during runtime
  def call(conn, sleep: milliseconds) do
    :timer.sleep(milliseconds)
    conn
  end
end

And then in endpoint.ex or router.ex

# ...

# it helps to think that Mix.env() works only during compilation, so don't use it in a function
# it's ok to use it in a module (endpoint) or in a macro (scope/pipeline in a router)
if Mix.env() == :dev do
  plug MyApp.Plugs.SlowResp, sleep: 1000 # 1 second in ms
end
# ...
1 Like

Most browsers have this built in now using the dev tools.

4 Likes

Thanks, that’s it!