After implementing countdown timers in JS you are able to easily create and remove timers anywhere in your web app. But the timers you create this way never send any information to the server. You can't do some action in the Elixir app when the time runs out. In this post we will create a live component to deal with that. I will use the live component subscription for convenience too, but it shouldn't be too hard to adapt it to the normal live component.
Adapting timers to the Phoenix hook
Before we can create a live component, we need a hook and to adapt timer functions to how Phoenix hooks need them to look and work.
const TIMERS = { handler: null, timers: {} };
export const LiveTimer = {
mounted() {
this.updated();
start_timers();
},
updated() {
if (this.lastSeconds != this.el.dataset.secondsLeft) {
this.lastSeconds = this.el.dataset.secondsLeft;
TIMERS.timers[this.el.id] = parseInt(this.lastSeconds) * 1000;
}
set_timer(this.el, TIMERS.timers[this.el.id]);
},
deleted() {
delete TIMERS.timers[this.el.id];
},
};
function start_timers() {
if (TIMERS.handler !== null) {
return;
}
let last_time = Date.now();
TIMERS.handler = setInterval(() => {
const now = Date.now();
const diff = now - last_time;
last_time = now;
for (const el of document.getElementsByClassName("timer")) {
const time = TIMERS.timers[el.id] - diff;
TIMERS.timers[el.id] = time;
set_timer(el, time);
}
}, 1000);
}
function set_timer(element, time) {
// Same as in js timers post.
}
The start_timers function is pretty much the same thing as in the JS timers post.
Only real change is that element's time is stored in a variable instead of in the element itself.
We have to do this because element may be updated and its attributes may be reset,
so the time left will always reset to the original value, messing our time calculation.
Because of this reason, the updated() function in the hook updates TIMERS.timers
only when the dataset value changes between calls.
When it happens, that means the timer's end time changed in the Elixir part.
set_timer is called either way, because updated() call means the element got re-rendered
and our inner text showing time remaining is gone.
Live component itself
Now we will create a live component.
defmodule MyAppWeb.LiveComponent.Timer do
use MyAppWeb, :live_component
use MyAppWeb.LiveComponent.MessagePasser
def initial_load(socket) do
{:ok, set_timer(socket, socket.assigns.end_time)}
end
def do_update(new_assigns, socket) do
old_time = socket.assigns.end_time
socket = assign(socket, new_assigns)
socket =
if DateTime.compare(old_time, socket.assigns.end_time) != :eq do
set_timer(socket, socket.assigns.end_time)
else
socket
end
{:ok, socket}
end
def set_timer(socket, timeout_time) do
now = DateTime.utc_now()
if DateTime.after?(timeout_time, now) do
key = System.unique_integer()
send_message_after!(
socket.assigns.id,
{__MODULE__, key},
DateTime.diff(timeout_time, now, :millisecond)
)
assign(socket, timer_key: key, timeout_time: timeout_time)
else
assign(socket, timer_key: nil, timeout_time: nil)
end
end
attr :end_time, DateTime, required: true
slot :time_out_block, required: true
slot :time_block, required: true
def render(assigns) do
~H'''
<span>
<%= if is_nil(@timeout_time) do %>
{render_slot(@time_out_block)}
<% else %>
{render_slot(@time_block, %{id: @id, timeout_time: @timeout_time})}
<% end %>
</span>
'''
end
def handle_message({__MODULE__, timeout_key}, socket) do
with ^timeout_key <- socket.assigns.timer_key,
true <- DateTime.after?(DateTime.utc_now(), socket.assigns.timeout_time) do
{:noreply, assign(socket, timeout_time: nil)}
else
false -> {:noreply, set_timer(socket, socket.assigns.timeout_time)}
_ -> {:noreply, socket}
end
end
attr :values, :map, required: true
@doc """
Countdown timer, counts (end - now) to 0 in HH:MM:SS format.
"""
def render_timer(assigns) do
now = DateTime.utc_now()
seconds_left = DateTime.diff(assigns.values.timeout_time, now)
assigns = assign(assigns, seconds_left: seconds_left)
~H'''
<span
data-seconds-left={@seconds_left}
class="timer"
phx-hook="LiveTimer"
id={@values.id}
></span>
'''
end
end
In initial_load we have to prepare a message to be sent when timer value reaches 0.
We also do this in case the end time changes when element updates.
In the message we send a unique integer to avoid the need to cancel old messages.
Instead, in handle_message we can just check
if the key for the timeout is the same as when it was last set.
In handle_message when we send timeout_time to nil we could also call some
callback given in attributes to the live component if the need ever arises.
In render we need two blocks, one with things to show when time runs out,
which can be something like "thing should happen soon" while waiting for
a message from some PubSub. Or fetch some data and show it.
The second block is for rendering the timer itself.
In theory it could be hardcoded render_timer function,
but I did it in a more generic way to allow showing some stuff along the timer,
but not when it runs out.
Also allowing us to ignore the timer itself and show an enigmatic message like
"something will happen soon" if that's what you need in a given situation.
The block gets data, which can be directly passed to render_timer,
so it can just render that function as a normal component.
Usage
With our live component ready, we can use it in live views and components. Let's create a component showing the timer that shows the time until the next day.
defmodule MyAppWeb.Serverle.QuoteGuesser.MainInfo do
use MyAppWeb, :live_component
use MyAppWeb.LiveComponent.MessagePasser
alias MyAppWeb.LiveComponent.Timer
def initial_load(socket) do
{:ok, set_tomorrow(socket)}
end
def handle_message(:set_tomorrow, socket) do
{:noreply, set_tomorrow(socket)}
end
defp set_tomorrow(socket) do
tomorrow_date = Date.utc_today() |> Date.add(1)
tomorrow = DateTime.new!(tomorrow_date, Time.new!(0, 0, 0))
now = DateTime.utc_now()
send_message_after!(
socket.assigns.id,
:set_tomorrow,
DateTime.diff(tomorrow, now, :millisecond)
)
assign(socket, tomorrow: tomorrow)
end
def render(assigns) do
~H"""
<div>
Tomorrow will start in:
<.live_component module={Timer} id="tomorrow_timer" end_time={@tomorrow}>
<:time_out_block>Any time now...</:time_out_block>
<:time_block :let={timer_values}>
<Timer.render_timer values={timer_values} />
</:time_block>
</.live_component>
</div>
"""
end
end
Upon running, it should show something like Tomorrow will start in: 00:49:12.
And that concludes the undertaking. Now your app can have timers counting down and showing different messages when time runs out.