Search code examples
javascriptmutation-observers

MutationObserver for only the last mutation


I'm using the MutationObserver to save position changes in a draggable object.

It looks like this:

 let observer = new MutationObserver( (mutations) => {
        mutations.forEach( (mutation) => {
            this.builderData[element.id].$position.left = element.style.left;
            this.builderData[element.id].$position.top = element.style.top;
            this.saveBuilderData();
        });
    });
    observer.observe(element, { attributes : true, attributeFilter : ['style'] });

However, this run for every pixel changed, so it is a lot saving operations being ran. I would like to only save after it has stop mutating for about 1 second, or that each callback excludes the previous one. I already did something like this with RxJava, but did not worked with MutationObserver.

Any ideas?


Solution

  • You could add a simple 1 second delay via setTimeout.

    This way previous callbacks are discarded and the style is only changed after 1 second of inactivity:

    let timer;
    let observer = new MutationObserver( (mutations) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        mutations.forEach( (mutation) => {
            this.builderData[element.id].$position.left = element.style.left;
            this.builderData[element.id].$position.top = element.style.top;
            this.saveBuilderData();
        });
      }, 1000);
    });
    observer.observe(element, { attributes : true, attributeFilter : ['style'] });