Kyle
Kyle

Reputation: 2872

Handling a series of DOMNodeInserted events as a single event in JavaScript

I am applying an event listener function when elements are inserted into the document via the DOMNodeInserted event. Elements are inserted in rapid succession, but I'd only like to have my function executed once per batch of element insertions.

I have tried using a boolean variable with global scope within my closure to denote whether or not the function called by the listener should actually take the action, coupled with setTimeout to reset this variable after the events have finished firing.

jQuery is being used for other functionality within this project, so it is an open option to consider here, but perhaps the abstraction is not incredibly helpful in this case. I have noticed the .one() method. Perhaps it is possible to bind an event handler which gets cancelled as soon as it is fired once and then re-established with the timeout?

Suggestions?

Upvotes: 1

Views: 1192

Answers (1)

Na7coldwater
Na7coldwater

Reputation: 1414

You could use the method that you suggested (using .one() and reattaching after a timeout), but it sounds like debounce (waiting until a burst of function calls ends before calling the handler, or calling the handler only once at the beginning of a batch of function calls) is what you're looking for. You could try John Hann's implmentation of bebounce or try Ben Alman's jQuery debounce plugin.

Upvotes: 2

Related Questions