问题
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.
回答1:
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);
来源:https://stackoverflow.com/questions/1626496/javascript-jquery-setinterval-clearinterval