javascript/jQuery setInterval/clearInterval

倾然丶 夕夏残阳落幕 提交于 2019-12-30 07:04:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!