> ## Content Index
> Fetch the complete content index at: https://til.codes/llms.txt
> Use this file to discover other available public pages before exploring further.

# Add latency tracking to phoenix live view apps.
- URL: https://til.codes/add-latency-tracking-to-phoenix-live-view-apps/
- Published: 2022-10-16T05:31:34.000Z
- Updated: 2022-10-16T07:50:25.000Z
- Description: Add latency tracking to phoenix live view apps
- Author: Manu Ajith
- Tags: elixir, phoenix, liveview, #Import 2024-07-13 21:01

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

```javascript
// 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

```elixir
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.

```html
# 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](https://github.com/fly-apps/live%5Fbeats/commit/65f307b1fae3c41879a5ef69ee51ea53a968e645?ref=til.codes)