Ajax中的计时器-抢占 [英] Timer in Ajax - Preemption

查看:87
本文介绍了Ajax中的计时器-抢占的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这件事在我脑海里已经长了一段时间,无论它是否在AJAx中给定的定时器必须在此之后发送另一个请求,如果它小于请求的文件完成其请求所花费的实际时间,该怎么办?操作.

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.

例如,考虑以下代码,

<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>

此处指定的计时器为100毫秒,每100毫秒将请求文件get_content_home.php.如果get_content_home.php需要500毫秒才能完成其操作该怎么办.get_content_home.php是否会被抢占并再次被请求?否则计时器将等待并自行延迟.

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.

提前谢谢.

推荐答案

由于ajax请求处于循环状态,因此比您想象的要糟糕.

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

实际上会发生什么:

  1. window.setInterval 调用 timeLeft

timeLeft 调用AJAX请求一次 get_content_home.php .

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

假设一个AJAX调用耗时500毫秒,那么您将在第一个AJAX请求返回某些内容之前执行此操作五次(因此,在一个结果之前需要5x .item 个调用的数量).

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).

要停止这种疯狂行为,请将您的AJAX调用置于循环之外,然后将 window.setInterval 放入AJAX回调函数中:

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);
  }
});

,并在开始时仅调用一次 timeLeft(); .

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

这篇关于Ajax中的计时器-抢占的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆