Search code examples
javascriptmutation-observers

MutationObserver override newest mutation


I'm trying to wait till a Mutation event kicks to override the value it just received. Before I was trying to apply it normally, but then it kept being overriden by the other value that is given from the 3rd party I can't control.

/** Intercept changes in select2-drop positioning **/
var MutationObserver = window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log("Override existent new found top value with -> " + newHeight);
        $(".select2-drop-active").css({'top':newHeight+"px"});
    });    
});

After I try this code, I think it enters in a loop cause my Chrome freezes and the memory starts increasing rapidly

Is there a way to stop the continous calls in Mutations ?


Solution

  • You can pause your mutation observer at any time by calling observer.disconnect

    So, depending on your use case, you might do something like this:

    var MutationObserver = window.WebKitMutationObserver;
    
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log("Override existent new found top value with -> " + newHeight);
            $(".select2-drop-active").css({'top':newHeight+"px"});
        });
        observer.disconnect();
        console.log('pausing the observer');
        // If needed for your use case, start observing in 1 second
        setTimeout(() => observer.observe(), 1000);
    });