2012-07-11 63 views
1

我setIntervel()有一个函数,我想停止这个函数的执行explicitly.How我能做到这一点???功能是..如何停止执行JavaScript间隔函数?

function autoLoad(chatboxtitle, msgId) { 
    setInterval(function() { 
     if (msgId != '') { 
      $.ajax({ 
       type: "POST", 
       url: "../WebService1.asmx/GetMessagesDetail", 
       data: '{ "messageID": "' + msgId + '" }', 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       async: true, 
       cache: false, 
       success: function(msg) { 
        $("#chatbox_" + chatboxtitle + ".chatboxcontent").empty(); 
        $("#chatbox_" + chatboxtitle + ".chatboxcontent").append(msg.d); 
        $contentLoadTriggered = false; 
       }, 
       error: function(x, e) { 
        alert("error"); 
       } 
      }); 
     } 
    }, 8000); 
} 
+3

将'setInterval()'的返回值存储到变量中,并调用'clearInterval()'。 – 2012-07-11 13:49:21

+1

除了Michael所说的,你是否考虑阅读一些['setInterval()'文档](https://developer.mozilla.org/en/DOM/window.setInterval)? – nnnnnn 2012-07-11 13:51:34

回答

10

如果你的意思是退出功能但不能停止时间间隔(所以函数会再次触发),您只需要从函数return

如果您的意思是停止间隔,即停止再次触发的功能,则需要为变量中的间隔分配一个参考,然后在/根据需要时清除它。

var intie = setInterval(function() { alert('hello'); }, 5000); 
clearInterval(intie);