7

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?

2
  • You can use debounce to reduce amount of stored information Commented Nov 22, 2017 at 12:27
  • I wish to see a better answer here. Commented Jun 23, 2018 at 6:05

1 Answer 1

10

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'] }); 
Sign up to request clarification or add additional context in comments.

1 Comment

It worked great, dude! I tried using timeout, but I didn't knew about this clearTimeout method =(. Cheers man!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.