Skip to content Skip to sidebar Skip to footer

How Do I Create A Javascript Listener Function That Will Perform An Action When A Condition Is True?

I'm using a third party javascript that has given me a lot of need for listeners. For instance, when a certain div has been loaded, I want to do something with it. It changes style

Solution 1:

functionconditionListener(callback){
    if(typeof callback !== 'function') return;

    var interval, callback = callback;

    interval = setInterval(function() {
        if(true/* some condition */){
            callback();
            clearInterval(interval);
        }
    }, 500);
}

var listener = newconditionListener(function() {
    /* ... do work ... */
});

http://jsfiddle.net/M26XS/

Solution 2:

I wrote this function once which looks like it does basically what you would want:

functionpollUntilTrue(conditionFunc, afterTrueFunc, timeout) {
    var __xinterval = setInterval(function() {
      var res = conditionFunc();
      if (res === true) {
        clearInterval(__xinterval);
        afterTrueFunc();
      }
    }, timeout);
  }

you would use it with your code like this:

pollUntilTrue(function() {
   return ($('popup') && $('popup').style.width == '500px');
}, 
function() {
  $('popup').style.width = '0';
}, 500);

Adjust the timeout to suite your needs

Solution 3:

Why don't you just accept a condition and an action? that would make it much simpler.

functionwhenTrue(condition, action) {     
   if (condition) {         
      action();     
   }     
  else {
         setTimeout("whenTrue('"+condition+"',"+action+", '"+stop_on+"')", 500); 
 }

}

and then you can provide the condition when calling the function, it would look like this:

whenTrue(($('popup') && $('popup').style.width == '500px') &&
          $('popup').style.width === '0', someAction); 

Post a Comment for "How Do I Create A Javascript Listener Function That Will Perform An Action When A Condition Is True?"