从文件中停止间隔设置间隔

时间:2016-04-12 12:20:34

标签: javascript php jquery ajax

如果我有名为index.phpfetch.php

的文件

index.php包含:

<script>
    $(document).ready(function(){

    setInterval(function(){
        $('#fetch').load('fetch.php')
    }, 1000);

});
</script>
<div id="fetch"></div>

fetch.php包含:

 $sql = "SELECT * FROM posts ORDER BY id DESC LIMIT 20";
    $result = $con->query($sql);

    if ($result->num_rows > 0) {

        while($row = $result->fetch_assoc()) {

           echo '

               <div>'.$row['post'].'</div><textarea id="comment" placeholder="Comment"></textarea><button id="btn">Comment</button>
';

    }}

我有一个问题,Interval每1秒重新加载一次,每当我点击文本区域时它也会重新加载。有没有办法通过单击code.php中的文本区域然后通过按钮将其设置回来来停止index.php中的间隔...

我一直在点击文本区域来存储到db中的单词commenting并将其设置为空白:

setInterval(function(){
            $('commenting').load('fetch.php')
        }, 1000);

按下按钮后将其设置回

setInterval(function(){
            $('#fetch').load('fetch.php')
        }, 1000);

但它还需要重新加载整个index.php页面以将$(&#39; #fetch&#39;)更改为$(&#39;评论&#39;)

所以我想知道有没有办法停止包含在该间隔内的文件的间隔?

2 个答案:

答案 0 :(得分:2)

当textarea获得/失去焦点时,您可以停止/启动间隔。试试这个:

$(document).ready(function() {
    var timer; 

    function startInterval() {
        timer = setInterval(function(){
            $('#fetch').load('fetch.php')
        }, 1000);
    }

    $('#fetch textarea').on({
        focus: function() {
            clearInterval(timer);
        },
        blur: function() {
            startInterval();
        }
    });

    startInterval(); // on load
});

我假设您正在构建聊天系统的代码结构。如果是这样,你应该调查使用websockets,因为AJAX轮询是服务器密集型的,并且不能很好地扩展。

答案 1 :(得分:0)

您正在寻找函数clearInterval()。

在变量中设置间隔,然后在需要时设置clearInterval()。

<script>
    $(document).ready(function(){

      abc = setInterval(function(){
        $('#fetch').load('fetch.php')
      }, 1000);


      // Conditions bla bla bla
      clearInterval(abc);
    });
</script>