1

Is there a smarter solution to wait until a node exists without using an interval or a fixed retry time?

Currently, I do such like this:

let interval = setInterval(function () {
    let neededElement = document.querySelector("small > time");
    if (neededElement !== null) {
        clearInterval(interval);

        ...code...
    }
}, 100);

What bothers me is that it always waits blindly. If the timing is low, it consumes resources unnecessarily and if it is high, it reacts too slowly to changes. And if the node never exists, it consumes resources unnecessarily in the background.

Probably a mutations observer would be a solution. But seems also not very slick to me, especially if I need this often. Or I would need some kind of (factory) function to build mutation observers.

EDIT:

The main problem of the mutation observer in my use case is the reusability in a script and the accuracy. Because nodes that do not exist yet cannot be observed. Therefore you have to go to higher nodes where it is sure that they exist immediately. But then the observer reacts also on unimportant changes. Depending upon use case these can be very many. So in the end you probably save less resources than with an interval.

edass
  • 45
  • 7
  • 1
    Yes, mutation observer is probably your best solution. It fill fire as soon as new node created and will sit dormant otherwise. – vanowm Aug 17 '21 at 18:01
  • That is true. Check this out: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – rexess Aug 17 '21 at 18:02
  • The questions is to make it usable for multiple nodes in one script and also for a NodeList like `document.querySelectorAll("small > time")` – edass Aug 18 '21 at 15:23
  • In the case of the NodeList, if I define a higher parent node it would react to changes that I don't care about. That's what I mean, that the mutation observer solution is not very smooth in cases you want to use it on multiple nodes at once. – edass Aug 18 '21 at 15:31
  • Reusing MutationObservers: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#reusing_mutationobservers – edass Aug 18 '21 at 18:25

0 Answers0