javascriptcustom-events

Custom event for countdown javascript


How do I create a custom event for when a timer is at zero. I call my custom element in another custom element and I want something to happen when the timer is at zero. I have a hard time understanding custom events, and I'm struggling with seeing how to use one in my case and where to put the event-listener. This is my countdown element:

  class extends HTMLElement {
  constructor () {
      super()
      this.attachShadow({ mode: 'open' })
        .appendChild(template.content.cloneNode(true))
      this._div = this.shadowRoot.querySelector('div')
    }

    timer (limit = 20) {
      let startingTime = limit
      const timer = this.shadowRoot.querySelector('#timer')

      setInterval(updateInterval, 1000)

      function updateInterval () {
        if (startingTime >= 0) {
          const seconds = startingTime % 60
          timer.textContent = `00:${seconds}`
          startingTime--
        } else { timer.textContent = '00:0' }
      }
    }

    connectedCallback () {
      this.timer()
    }
  })

This is where I call the countdown element:

  customElements.define('quiz-questions',
  class extends HTMLElement {
   
    constructor () {
      super()
      this.attachShadow({ mode: 'open' })
        .appendChild(template.content.cloneNode(true))
      this._div = this.shadowRoot.querySelector('div')
      this._p = this.shadowRoot.querySelector('p')
      this._submit = this.shadowRoot.querySelector('#submit')
      this.result = []
    }

   timer (limit = 20) {
      const timer = document.createElement('countdown-timer')
      this._div.appendChild(timer)
      timer.timer(limit)
    }
  
   connectedCallback () {
      this.timer()
    }
})
```

Solution

  • Most idiomatic in this situation would be probably to use custom events:

    const timerElement = this;
    function updateInterval () {
        if (startingTime >= 0) {
            const seconds = startingTime % 60
            timer.textContent = `00:${seconds}`
            startingTime--
        } else {
            timer.textContent = '00:00'
            // dispatch a custom event
            const timeIsUpEvent = new CustomEvent('time-is-up');
            timerElement.dispatchEvent(timeIsUpEvent);
        }
    }
    

    and then in some other component:

    this.addEventListener('time-is-up', (event) => {
        // do smth about it!
    });
    

    Also you might want to check out this article: