← 返回首页
Live timer element
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search
    Search
    Light themeDark theme
    عربيDanskEnglishEspañolفارسیFrançaisIndonesiaItaliano日本語한국어РусскийTürkçeУкраїнськаOʻzbek简体中文
    back to the lesson

    Live timer element

    We already have <time-formatted> element to show a nicely formatted time.

    Create <live-timer> element to show the current time:

    1. It should use <time-formatted> internally, not duplicate its functionality.
    2. Ticks (updates) every second.
    3. For every tick, a custom event named tick should be generated, with the current date in event.detail (see chapter Dispatching custom events).

    Usage:

    <live-timer id="elem"></live-timer> <script> elem.addEventListener('tick', event => console.log(event.detail)); </script>

    Demo:

    Open a sandbox for the task.

    solution

    Please note:

    1. We clear setInterval timer when the element is removed from the document. That’s important, otherwise it continues ticking even if not needed any more. And the browser can’t clear the memory from this element and referenced by it.
    2. We can access current date as elem.date property. All class methods and properties are naturally element methods and properties.

    Open the solution in a sandbox.