Mark Sandman
Mark Sandman

Reputation: 3333

How to use setInterval() as an event listener

I've never used setInterval() and I need some advice as I can't get my head round this. I want to create some kind of event listener.

Say for example I want to check the length of options in a Select Menu however a third party script populates the content of the Select Menu via an Ajax request. Unfortunately I'm not allowed to touch the the third party script so I though about having a function that waits and listens for the content to be added and can then perform it's tasks.

say I have the following on my web page:

<select size="7" id="cat"> </select>

onload this gets filled with options like this:

<option value="Category 1">Category 1</option>
<option value="Category 2">Category 2</option>
<option value="Category 3">Category 3</option>
<option value="Category 4">Category 4</option>

I was going to add a function that also loads onLoad (or $(document).ready() to be exact) that will listen to the length of the options and if greater than zero we wish to do something (in this example an alert)

function checkLen(){

    if($('#cat option').size() > 0){
        return true;
       }else{
        return false;
       }

}


function takeDefault(){

    var ourInterval = setInterval("checkLen();", 1000);

       if(ourInterval == true){
           alert("Okay I will do something now");
           clearInterval(ourInterval);

       }

        // Now I will perform some other tasks
}

$(document).ready(function() {
   takeDefault();
});

Now this just doesn't work as I don't really understand. The if(checkLen == True) condition is only done once and I need this to be done every second until the select menu is populated.

Upvotes: 2

Views: 9140

Answers (2)

hvgotcodes
hvgotcodes

Reputation: 120138

ourInterval is NOT the return value of function executed by setInterval. It is the value you can use to cancel the interval.

Second, instead of checking at an interval, why not just register a listener on the input, and do something when it changes?

Something like

http://jsfiddle.net/BskPK/

Upvotes: 0

Yoshi
Yoshi

Reputation: 54649

For simplicity I used different elements, but the idea is still the same:

var listen = setInterval(function () {
    if ($('input').val().length > 0) {
        console.log('has changed, should call callback');
        clearInterval(listen);
    }
}, 1000);​

http://jsfiddle.net/suKCp/

For your case this should be something like (untested):

function takeDefault(){
  var ourInterval = setInterval(function () {
    if ($('#cat option').size() > 0) {
      alert("Okay I will do something now");
      clearInterval(ourInterval);
    }
  }, 1000);

  // Now I will perform some other tasks
}

Upvotes: 4

Related Questions