weixin_33670786 2018-06-05 14:02 采纳率: 0%
浏览 20

Ajax中的计时器-抢占[重复]

This question already has an answer here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/50705802/ajax-too-slow-recursion" dir="ltr">Ajax too slow - Recursion</a>
                            <span class="question-originals-answer-count">
                                (1 answer)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2018-06-16 11:16:18Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

So this thing was going in my mind for a long time whether the timer that is given in an AJAx after which it has to send another request, what if it is smaller than the actual time taken by the requested file to complete its operation.

for example, consider the below code,

<div class="item"></div>
<script>
function timeLeft() {
  $(".item").each(function() {
    $this = $(this);
    var dataString = {s: "//some data", st: "<?echo $stamp?>"};
    $.ajaxSetup({cache:false});
    $.ajax({
      type: "POST",
      url: "get_content_home.php",
      dataType: "html",
      data: dataString, 
      success: function(result) {
        $this.html(result);
      }
    });
  });
}
window.setInterval(function() {
  timeLeft();
}, 100);
</script>

the timer given here is 100ms and the file get_content_home.php will be requested every 100m. What if get_content_home.php takes 500ms to complete its operations. Will the get_content_home.php be preempted and will be requested again? or will the timer wait and delay itself.

Thanks in advance.

</div>
  • 写回答

1条回答 默认 最新

  • weixin_33724659 2018-06-05 14:14
    关注

    It's worse than you thought since the ajax request is in a loop.

    What's gonna happen is actually :

    1. window.setInterval call timeLeft

    2. timeLeft call the AJAX request to get_content_home.phpone time for each .item element.

    3. Let's say one AJAX call take 500ms, you'll do this five time before the first AJAX request return something (hence 5xnumber of .item calls before one result).

    To stop this craziness, put your AJAX call outside of the loop and put the window.setInterval in the AJAX callback function:

    $.ajax({
      type: "POST",
      url: "get_content_home.php",
      dataType: "html",
      data: dataString, 
      success: function(result) {
        $this.html(result);
        window.setTimeOut(function() {
          timeLeft();
        }, 100);
      }
    });
    

    and call timeLeft(); just once at the start.

    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)