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);
}
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With