<live-timer>

๐Ÿ’พ replit

// 1. define new element
class LiveTimer extends HTMLElement {

    /* ---------- life cycle callbacks ---------- */

    // triggers when element is added to page
    // (or when HTML parser detects it)
    connectedCallback() {

        this.render();

        // โญ๏ธ start timer
        this.startTimer();
    }

    disconnectedCallback() {
        // โญ๏ธ important to let the element be garbage-collected
        this.cancelTimer(); 
    }

  /* ---------- helper methods ---------- */
  
    render() {

        // show a nicely formatted time.
        // โญ๏ธ ๆณจๆ„๏ผš้€™่ฃก่จญๅฎš็š„ๆฑ่ฅฟๅฑฌๆ–ผ light DOMโ—๏ธ
        this.innerHTML = `
            <time-formatted 
                year="numeric" 
                month="long" 
                day="numeric" 
                hour="numeric" 
                minute="numeric" 
                second="numeric"
                time-zone-name="short">
            </time-formatted>
        `;

        // โญ๏ธ reference to <time-formatted> child
        this.timeChild = this.firstElementChild;
    }

    // update
    update(){

        this.date = new Date();

        // โญ๏ธ update child
        this.timeChild.attr('datetime', this.date);

        // โญ๏ธ dispatch 'tick'
        let tick = new CustomEvent('tick', {
            detail: this.date
        });

        this.dispatchEvent(tick);
    }

    // start timer
    startTimer(){
        // โญ๏ธ ๆณจๆ„๏ผšไธ่ฆๅฏซๆˆใ€Œ setInterval(this.update, 1000) ใ€โ—๏ธ
        //         ไธ็„ถๆœƒๅคฑๅŽป `this` contextโ—๏ธ
        this.timer = setInterval(() => this.update(), 1000);
    }

    // cancel timer
    cancelTimer(){
        // โญ๏ธ ๆณจๆ„๏ผšไธๆ˜ฏ this.timer = nullโ—๏ธ
        clearInterval(this.timer);
    }
}

// 2. register new element
customElements.define("live-timer", LiveTimer);

Last updated