Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver only called once if it inside set timeout

If I keep observe inside setTimeout then updateChild called on 1st render, but if I removed setTimeout then it works on every render. Could someone please help me how to solve this problem as I need the setTimeout?

private observer = new MutationObserver(this.updateChild.bind(this));

updateChild(mutationsList: MutationRecord[], observer: MutationObserver) {
    console.log('updated');
  }

handelMouseEnter(){
      if (this.popupTimer) {
        clearTimeout(this.popupTimer);
      }
      this.popupTimer = setTimeout(() => {
        this.container = document.createElement('div');
        document.body.appendChild(this.container);

        ReactDOM.render(
          <Layout innerRef={e => (this.myRef = e)}>{this.props.children}</Layout>,
          this.container,
        );

        if (this.myRef) {
          this.observer.observe(this.myRef, { childList: true });
        }
   }, 500);
}
like image 725
Sanjan Avatar asked Mar 27 '26 22:03

Sanjan


1 Answers

A MutationObserver fires its callback as many times whether declared inside or outside a setTimeout callback.

Example (JSBin demo) :

const paragraphElement = document.querySelector('p');
// Update body with current time every second, which will trigger MutationObserver
setInterval(() => {
    paragraphElement.textContent = new Date().toLocaleString();
}, 1000);
// Create a MutationObserver outside setTimeout
new MutationObserver(() => console.log(`Outside setTimeout : ${paragraphElement.textContent}`))
    .observe(paragraphElement, { childList: true });
// Create a MutationObserver inside setTimeout
setTimeout(
    () => new MutationObserver(() => console.log(`Inside setTimeout : ${paragraphElement.textContent}`))
        .observe(paragraphElement, { childList: true }),
    500
);
like image 74
KaKi87 Avatar answered Mar 30 '26 12:03

KaKi87