Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to do something while HTMLNode exist?

I have custom class for timer. It returns HTMLDivElement, which counts down to 0

/*
Example:

Create timer
let timer = new Timer('div', 'timer', timeForGame).render(); 

Timer fires event when clock id down to 0
timer.addEventListener('countDown', () => { console.log("Timer is out") })
*/
export default class Timer extends Component{
    protected time: number;
    protected event: CustomEvent;
    constructor(tagName: string, className: string, time: number) {
        super(tagName, className);
        this.time = time;
        this.event = new CustomEvent("countDown")
    }

    startTimer(){
        let countdown = this.time * 1000;
        this.container.textContent = String(countdown / 1000);
        const countingDown = () => {
            console.log(countdown / 1000, " seconds");
            countdown -= 1000;
            this.container.textContent = String(countdown / 1000);
            if (countdown === 0){ 
                this.container.dispatchEvent(this.event);
                clearInterval(Timer) 
            }
        }
        const Timer = setInterval(countingDown, 1000);
    }

    render() {
        this.container.innerHTML = String(this.time);
        this.startTimer();
        return this.container;
    }
}

How do I track if the element is alive? I tried some variations of this

while(document.querySelector('.timer') !== null){
  setTimeout(() => {
    console.log('i exist')
  }, 0);
}

But it didn’t work. Or should I create another event?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use an interval instead of a while loop.

setInterval(()=>{
  if (document.querySelector('.timer') !== null) {
    console.log('i exist')
  }
}, 100)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading