Add latency tracking to phoenix live view apps.

Adding latency tracker to a phoenix application provides some valuable insights for UX.

Latency tracking can be added to any phoenix live view application using a few lines of codes as below:

Adding the hook

// assets/js/app.js

Ping: {
  mounted() {
    this.timer = setInterval(() => {
      let beforeTime = (new Date().getTime())
      this.pushEvent("ping", {}, resp => {
        let rtt = (new Date().getTime()) - beforeTime
        this.el.innerText = `Ping: ${rtt}ms`
      })
    }, 1000)
  },
  destroyed() { clearInterval(this.timer) }
}

Followed by adding the handle_event/3 to the liveview

def handle_event("ping", _, socket) do
  {:reply, %{}, socket}
end

And finally, adding a few lines of html to render the latency info on the template.

# templates/layout/live.html.heex

<div class="relative">
  <div id="ping-container" class="fixed bottom-0 right-0 bg-gray-900 text-gray-200 px-2 rounded-tl-md text-sm w-[114px] min-w-max" phx-update="ignore">
    <span id="ping" phx-hook="Ping"></span>
  </div>
</div>

Copied from LiveBeats app

Reference: https://github.com/fly-apps/live_beats/commit/65f307b1fae3c41879a5ef69ee51ea53a968e645