views:

5532

answers:

1

i'm using setInterval to check if a p(html paragraph) has a certain text value. if it has it i want to clear interval an continue code flow. i'm using this in a jQuery plugin so if the paragraph has tat text value i want to clear interval and then continue with a callback function. so i tried something like this:

var checkTextValue = setInterval(function(){
                          var textVal = $('p').text();
                          if(textVal == 'expectedValue'){
                              clearInterval(checkTextValue);
                              callback();
                          } 
                     },10);

and the callback function it's a simple alert. My problem is that the alert is called endlessly. How can i write my code to do it right? thanks.

+3  A: 

Use setTimeout instead of setInterval.

Something like:

var checkTextValue = setTimeout(function() {
    var textVal = $('p').text();
    if (textVal == 'expectedValue'){
        callback();
    } else {
        setTimeout(arguments.callee, 10);
    }
},10);
Anton
In general, I agree that this is a better approach. But doesn't really answer the question of why that code doesn't work.
Sixten Otto
ok, this works but now the problem is that in firefox i still get that animation and loading bar like the page is loading and the message transferring data...
kmunky
That should be unrelated. setTimeout has to do with internal method calls, while the Firefox loading indicator has to do with external HTTP requests.
Anton