在计时器上重复/循环ajax调用 - 即使超时也是如此

时间:2017-12-11 15:03:30

标签: javascript jquery ajax settimeout

我们有一个需要每秒更新的显示板。对服务器的AJAX调用触发存储过程,这是一个非常简单的SELECT语句,执行只需几毫秒。

最初,由于网络延迟(或太阳黑子,或谁知道什么),这个AJAX过程会(偶尔很少)超时。通过调整我们处理计时器的方式并将TerminateProcess设置为0,我们可以让它现在运行稳定并且超时永远不会发生......但是。

话虽如此,我仍然担心超时可能仍然会发生。如果发生,目标是它会继续前进。基本上,忽略超时,再试一次......永远。没有MaxError,RetryLimit或TryCount等等。

这就是我现在所拥有的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <!--BOOSTRAP-->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link rel="stylesheet" href="OwlCarousel/dist/assets/owl.carousel.min.css">
     <link href="jqueryUI/jquery-ui.min.css" rel="stylesheet">
    <link rel="stylesheet" href="OwlCarousel/dist/assets/owl.theme.default.min.css">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
      <link rel="stylesheet" type="text/css" href="maincss/style.css">
</head>
<body>
<!-- NAVIGATION ->START -->
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="../home"><strong>Brand</strong></a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="../../villamimoza"><strong>Home</strong> <span class="sr-only"></span></a></li>
        <li><a href="../roomsandoffers"><strong>Rooms and offers</strong></a></li>
        <li><a href="../about"><strong>Our story</strong></a></li>
        <li><a href="../directions"><strong>How to find us</strong></a></li>
        <li><a href="../contact"><strong>Contact us</strong></a></li>
      </ul>
        </li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<!-- HEADER-end-->
<!-- CAROSUEL-->
<div class="owl-carousel owl-theme">
    <div class="item"><img src="https://.postimg.org/feb06bivt/IMG_5752-_Edit.jpg"/> </div>
    <div class="item"><img src="https://s.postimg.org/u8zlkhsgp/IMG_5759-_Edit.jpg"/> </div>
    <div class="item"><img src="https://.postimg.org/bfdsnhu8p/IMG_5767-_Edit.jpg"/></div>
    <div class="item"><img src="https://.postimg.org/6pj9l5duh/IMG_5771-_Edit.jpg"/> </div>
    <div class="item"><img src="https://.postimg.org/7ci6aoaqh/IMG_5774-_Edit.jpg"/> </div>
    <div class="item"><img src="https://.postimg.org/989jzkoyh/IMG_5829-_Edit.jpg"/> </div>
    <div class="item"><img src="https://.postimg.org/9v3vbcwgp/IMG_5835-_Edit.jpg"/> </div>
    <div class="item">
        <img src="https://.postimg.org/67spj1dnd/IMG_5840-_Edit.jpg"/> 
        </div>
</div>
<!-- CAROSUEL END-->

<div class="container">
    <div class='col-md-5'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker6'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <div class='col-md-5'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker7'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        $('#datetimepicker6').datetimepicker();
        $('#datetimepicker7').datetimepicker({
            useCurrent: false //Important! See issue #1075
        });
        $("#datetimepicker6").on("dp.change", function (e) {
            $('#datetimepicker7').data("DateTimePicker").minDate(e.date);
        });
        $("#datetimepicker7").on("dp.change", function (e) {
            $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
        });
    });
</script>
<!-- FOOTER START-->
<footer class="footer-distributed">

            <div class="footer-right">

                <a href="#"><i class="fa fa-facebook"></i></a>
                <a href="#"><i class="fa fa-twitter"></i></a>
                <a href="#"><i class="fa fa-linkedin"></i></a>
            </div>

            <div class="footer-left">

                <p class="footer-links">
                    <a href="#">Home</a>

                    <a href="#">Contats</a>

                    <a href="#">About</a>

                    <a href="#">FAQ</a>
                </p>
            </div>

        </footer>
<!-- FOOTER ->END-->

<!-- SCRIPTS-->
  <script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script><!-- jQuery-->
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script><!-- Bootstrap JS-->
 <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="OwlCarousel/dist/owl.carousel.min.js"></script><!--OWL js-->
<script src="js/home.js"></script><!-- Custom JS-->

<!-- SCRIPTS->END-->
</body>
</html>

timeout内的所有内容都很有效。没问题。并设置计时器(我相信),以便它等到一个GetData()完成后再尝试启动另一个。

我相信通过将setTimeout(function run() { // When the timer elapses, get the data from the server GetData(); setTimeout(run, _refreshRate); }, 1000); function GetData() { //console.log("Attempting to obtain the data..."); jQuery.ajax({ url: "something.ashx", type: "GET", contentType: 'application/json; charset=utf-8', success: function(resultData) { //console.log("Got the data."); ParseJson(resultData); // show the last refresh date and time $('#refreshTime').html(GetDateTime()); }, error : function(xhr, textStatus, errorThrown) { if (textStatus == 'timeout') { //console.log("Timeout occured while getting data from the server. Trying again."); // If a timeout happens, DON'T STOP. Just keep going forever. $.ajax(this); return; } }, timeout: 0, }); } 设置为ParseJson(resultData);意味着“永远不会超时”。

我的问题是:

我是否正确处理timeout超时?我在这个帖子中使用所选答案作为我的向导:

What's the best way to retry an AJAX request on failure using jQuery?

但我不需要retryLimit限制。

我也看过这些主题:

How to make the Ajax call again in case Time out error occurs

ajax timeout callback function

认为我已将所有信息归结为一个简单的解决方案,但我想要一些同行评审。有更好的方法吗?

2 个答案:

答案 0 :(得分:5)

我更喜欢只在当前完成时排队新呼叫的解决方案。类似......

function poll() {
  setTimeout(function () {
     GetData();
  }, 1000);
}

function GetData() {
    jQuery.ajax({
        url: "something.ashx",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function(resultData) {
            //...
        },
        error : function(xhr, textStatus, errorThrown) {
            //...
        },
        complete: function() {
           poll();
        },
        timeout: 0,
    });
}

poll();

这样,您的通话无论如何也不会有重叠的风险。

答案 1 :(得分:1)

function GetData() {
    //console.log("Attempting to obtain the data...");
    jQuery.ajax({
        url: "something.ashx",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function(resultData) {
            //console.log("Got the data.");
            ParseJson(resultData);
            // show the last refresh date and time
            $('#refreshTime').html(GetDateTime());
        },
        error : function(xhr, textStatus, errorThrown) {
            if (textStatus == 'timeout') {
                //console.log("Timeout occured while getting data from the server.  Trying again.");
                // If a timeout happens, DON'T STOP. Just keep going forever.
                $.ajax(this);
                return;
            }
         },
         timeout: 0,
    });
}

var myInterval = setInterval(getData, 1000)
// if you want to stop it elsewhere:
// clearInterval(myInterval)

而不是超时,你可以使用setInterval