Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript/jQuery setInterval/clearInterval

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.

like image 258
kmunky Avatar asked Mar 01 '23 03:03

kmunky


1 Answers

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);
like image 149
Anton Avatar answered Mar 12 '23 01:03

Anton