Home > Back-end >  How to do something while HTMLNode exist?
How to do something while HTMLNode exist?

Time:08-26

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?

CodePudding user response:

Use an interval instead of a while loop.

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