javascript/jQuery setInterval/clearInterval

kmu*_*nky 4 jquery plugins clear setinterval

我正在使用setInterval来检查ap(html段落)是否具有某个文本值.如果它有它我想清除间隔一个继续代码流.我在jQuery插件中使用它,所以如果段落有tat文本值我想清除间隔然后继续回调函数.所以我尝试过这样的事情:

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

和回调函数它是一个简单的警报.我的问题是无休止地调用警报.如何编写我的代码才能正确完成?谢谢.

Ant*_*ton 8

使用setTimeout而不是setInterval.

就像是:

var checkTextValue = setTimeout(function() {
    var textVal = $('p').text();
    if (textVal == 'expectedValue'){
        callback();
    } else {
        setTimeout(arguments.callee, 10);
    }
},10);
Run Code Online (Sandbox Code Playgroud)

  • 总的来说,我同意这是一种更好的方法.但是并没有真正回答为什么代码不起作用的问题. (2认同)