Detecting DOM changes

Recently, I have come across situations where I need to detect elements being added to the DOM and trigger some other function.

For example, I was working on combining the lightbox plugin with a Jquery iviewer plugin. The problem is the lightbox plugin creates various elements and the zoom plugin can work only after all the elements created by lightbox have been loaded. I used setTimeout initially, but that created race conditions.

In another situations I had to wait for a third party server response and DOM nodes being added before my code was executed.

To tackle these kind of situations I came up with a small polling function that would wait for the element to be created before doing something else. Without any more delay I present the idea implemented below:

var limit = 1000,
    iter = 0,
    timeout = 100,
    wnw = function () {
      if (iter > limit) {
          return false;
      if ($(element).length > 0) {
          //do something
          return true;
      else {
          setTimeout(wnw, timeout);
      iter += 1;

The function once executed calls itself at regular intervals(timeout) before checking if the element exits and doing the needful. If the functions has been called more than a specified number of times(limit) it simply exits deciding that the element would never be created.

This can also be extended to detect element removal. Of course, I suggest wrapping all this code in a module before using it.