We are currently successfully detecting mutations of target DOM elements within our page. We are now looking at aggregating certain properties of these target node mutations in a 'list' to send via an AJAX call for processing on the server. The callback from the server will allow us to modify attributes on these target elements en masse.
However, the problem is WHEN to make the first Ajax call. Obviously we know when the mutations start (thus adding to the list). However, we never know when they end (MutationObserver is idle) to then make our AJAX call. We could, of course, write a function that checks the size of the list, along with a period of time passed, to make our Ajax call that contains the contents of our aggregated list when the function wakes up.
Is this it or is there a better way of handling this?
Thoughts appreciated!
You can use a
debounce
function so that the function is only called after for a period of timep
Underscore js offers a nice debounce function which you can use as below:
So this will prevent your ajax call from being made until 1 second has elapsed since the last mutation and it will not fire if there was not a 1 sec since the previous mutation.
Here's perhaps the simplest implementation from an old version of underscore and a perf test comparing different implementations