0

我正在使用 jQuery,并且setInterval在执行 AJAX 请求时停止工作,该请求返回包含相同setInterval. 那是:

鉴于我有以下代码:

<div id="test_css_id">
  <a id="link_css_id" href="test_url.html">LINK</a>

  <script type="text/javascript">
    $('#link_css_id').click(function(event) {
      event.preventDefault();

      $.ajax({
        url:     $(this).attr('href'),
        type:    'PUT',
        success: function(data) {
          $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
        }
      });
    });

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

      function refreshFunction(){
        $.ajax({
          url:     'test_url.html',
          type:    'GET',
          success: function(data) {
            $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
          },
          complete: function(data) {
            clearInterval(refreshTimer); // Note: This'd not stop the setInterval.
          }
        });
      }

      refreshTimer = setInterval(refreshFunction, 1000); // milliseconds
    });
  </script>
</div>

click函数内的 AJAX 请求成功运行时,则重新加载上述代码(注意:在其中呈现datareplaceWith内容与上述代码完全相同,包括 JavaScript)。但是,setInterval它不是“覆盖”/“停止”,因此浏览器运行一次比setInterval我每次单击LINK. 运行时不会发生同样的情况refreshFunction。但是,根据之前的点击量LINK,甚至refreshFunction导致setInterval运行的次数越来越多。

当 AJAX 请求成功时如何停止setInterval运行以便只setInterval运行一个?

4

1 回答 1

1

您需要在执行更换之前清除计时器。为此,您还需要在click回调中可以访问 timer 变量。在这种情况下,我已将计时器设为全局,但还有其他方法可以做到这一点,我将由您决定。

<div id="test_css_id">
  <a id="link_css_id" href="test_url.html">LINK</a>

  <script type="text/javascript">
    var refreshTimer;  //******************** Timer is now global
    $('#link_css_id').click(function(event) {
      event.preventDefault();

      $.ajax({
        url:     $(this).attr('href'),
        type:    'PUT',
        success: function(data) {
          //************* Clear interval if it exists before replacing code.
          clearInterval(refreshTimer);
          $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
        }
      });
    });

    $(document).ready(function() {
      function refreshFunction(){
        $.ajax({
          url:     'test_url.html',
          type:    'GET',
          success: function(data) {
            $('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
          },
          complete: function(data) {
            clearInterval(refreshTimer); // Note: This'd not stop the setInterval.
          }
        });
      }

      refreshTimer = setInterval(refreshFunction, 1000); // milliseconds
    });
  </script>
</div>
于 2013-09-19T17:39:46.213 回答