【问题标题】:How to stop setInterval();? [duplicate]如何停止 setInterval();? [复制]
【发布时间】:2014-08-11 12:29:14
【问题描述】:

我喜欢...

<div id="div"></div>
<script src="jquery.js"></script>
<script src="updater.js"></script>

我想从我的 .php 文件中获取数据的更新程序,所以可能类似于...

setInterval(function() {
    $.ajax({
        type: "GET",
        url: "test.php",
        success: function(html) {
             // html is a string of all output of the server script.
            $("#div").html(html);
       }
    });
}, 5000);

那么,很明显,test.php 的页面就足够了。

但是,我想停止 setInterval();当有人点击评论按钮 (textarea) 时。我知道,这里有一些;但他们不工作?

【问题讨论】:

  • P.S.那不是我的实际代码;只是一些随机的垃圾。但是,这就是我的格式。
  • 有关如何停止间隔的完整演示,请参阅 setInterVal 上的 JavaScript MDN 文档,特别是 Example 2 - The following example will continue to call the flashtext() function once a second, until you clear the intervalID by clicking the Stop button. - 相关代码位于停止按钮单击中。 - 希望这会有所帮助:)
  • @AwesomeE:我不确定你为什么觉得你的问题没有得到回答。你能告诉我们你还在寻找什么clearInterval 没有吗?据我们所知,您需要的代码在链接的“可能”重复项中,但也在每个答案中,除非除了您所说的之外还有其他要求。 clearInterval(intervalId) 将停止间隔 - 如何调用它取决于您。如果您只是想要一个完整的复制粘贴解决方案,请参阅this

标签: javascript


【解决方案1】:

Window.clearInterval,它接受一个intervalID 是您要取消的重复操作的标识符。这个ID是从setInterval().返回的

例子

var interVal = setInterval(function() {
    $.ajax({
        type: "GET",
        url: "test.php",
        success: function(html) {
             // html is a string of all output of the server script.
            $("#div").html(html);
       }
    });
}, 5000);

clearInterval(interVal); //Call the method when you want to clear it.

【讨论】:

    【解决方案2】:

    setInterval 函数将返回一个整数,用于标识该间隔。保存该整数以备后用,当您想清除间隔时,将其作为参数传递给clearInterval。

    例如:

    var myInterval = setInterval(function() {
        $.ajax({
            type: "GET",
            url: "test.php",
            success: function(html) {
                 // html is a string of all output of the server script.
                $("#div").html(html);
           }
        });
    }, 5000);
    

    然后当你想取消它时:

    clearInterval(myInterval);
    

    参考: http://www.w3schools.com/jsref/met_win_clearinterval.asp

    【讨论】:

      【解决方案3】:

      您可以使用clearInterval。它需要间隔的 Id 并清除它。

      在变量中获取您的setInterval。

      var interval = setInterval(function(){...},time);
      

      点击按钮后就可以了

      clearInterval(interval);
      

      DEMO

      【讨论】:

        猜你喜欢
        • 2014-06-18
        • 2010-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 2020-08-17
        • 1970-01-01
        • 2013-06-04
        相关资源
        最近更新 更多