To make our directive update asynchronously, we'll need to start a timer that re-renders the time elapsed.

Add a function that starts a periodic 3 second timer if it's not already started. Since directives are stateful, we can use a class field to store the timer's handle, and use that to start the timer only once:

time-ago.

Permalink to "time-ago."

Start the timer in the update lifecycle callback.

The default implementation of update simply calls render, but since update is not called during SSR, update is the right spot to start/subscribe to asynchronous tasks we don't want running on the server.

Add the update callback. Call ensureTimerStarted() and then return the result of render. Note that we only want the timer running if the directive is currently connected, so check isConnected before starting the timer:

It is possible for a template to be re-rendered after it has been disconnected.

In this case update will still be called, so you should always check isConnected before doing work that might require cleanup.

Our directive now starts a periodic timer the first time it is updated, although it doesn't do anything interesting yet.