如何定期解雇AJAX请求?

use*_*345 105 ajax jquery

<meta http-equiv="Refresh" Content="5">
Run Code Online (Sandbox Code Playgroud)

此脚本每5秒后重新加载或刷新页面.但我想用jQuery和AJAX调用来做.可能吗?

dre*_*ish 271

正如其他人指出的那样,setInterval和setTimeout都可以解决问题.我想强调一下我从Paul Irish的优秀视频中学到的更先进的技术:http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

对于可能最终花费比重复间隔更长的周期性任务(如慢速连接上的HTTP请求),最好不要使用setInterval().如果第一个请求尚未完成并且您启动另一个请求,则最终可能会出现多个请求消耗共享资源并相互挨饿的情况.您可以通过等待安排下一个请求直到最后一个请求完成来避免此问题:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();
Run Code Online (Sandbox Code Playgroud)

为简单起见,我使用成功回调进行调度.这样做的缺点是一个失败的请求将停止更新.为避免这种情况,您可以使用完整的回调:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();
Run Code Online (Sandbox Code Playgroud)

  • @RahulDole这是一个很好的问题,但它不是递归的.它不是直接从worker函数调用的,因此堆栈不会继续增长.对于你的第二点,检查setTimeout()的文档,你会看到它返回一个可以传递给clearTimeout()的数字id. (14认同)
  • @RahulDole如果你在chrome中使用console.trace()来查看函数的调用堆栈.setTimeout()调用的函数将具有非常短的堆栈,并且它肯定不会包含调用setTimeout()的函数. (7认同)
  • 这不是一个递归函数调用吗?如果是,那么可以让它反复运行很长一段时间,因为它是递归的吗?只要ajax保持成功执行,就可以是无限递归的情况 (3认同)

Tah*_*aza 33

是的,您可以使用JavaScript setTimeout()方法或setInterval()方法来调用您想要运行的代码.以下是使用setTimeout执行此操作的方法:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});
Run Code Online (Sandbox Code Playgroud)