每 X 分钟调用一个带有 AJAX 的文件,直到 Y 时间?

Call a file with AJAX every X minutes until Y time?

我有以下代码

$(document).ready(function() {
    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
    setInterval(function() {
        $('#chatresults').load('includes/chat.php');
    }, 3000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});

效果很好。这每 3000 毫秒加载一次页面,但它会永远加载一次,这意味着如果有人打开浏览器,我的服务器存储会被大量用完,因为它在另一个页面上运行 MySQL 查询。

我如何限制它使其每 3000 秒调用一次,但在 10 分钟后(或 X 加载后)它停止(直到页面为 refreshed/changed)?

我正在尝试其中一种答案,但它不起作用。我是 AJAX 菜鸟,我做对了吗?

if (counter == 12) {
    clearInterval(aux);
}
    $(document).ready(function() {
    $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will     only load the first number and will never refresh
aux = setInterval(function() {
    $('#chatresults').load('includes/chat.php');
}, 3000);
counter++;

    });

三个简单的步骤:

  1. 将 setInterval 分配给处理程序:

    auxHandler = setInterval(function() {
        $('#chatresults').load('includes/chat.php');
    }, 3000);
    
  2. 跟踪使用变量调用 ajax 的次数(例如:调用它 counter

    counter++;
    
  3. counter达到最大调用次数时,清除间隔:

    if (counter == MAX_NUM_CALLS) {
        clearInterval(auxHandler);
    }
    

在您的特定情况下,代码如下所示:

var intervalHandler;
var counter = 0;

$(document).ready(function() {
    $.ajaxSetup({ cache: false });
    intervalHandler = setInterval(function() {
        $('#chatresults').load('includes/chat.php');
        counter++;
        if (counter == 12) {
            clearInterval(intervalHandler);
        }
    }, 3000); 
});

您还可以在这个 jsfiddle 上看到它的工作原理:http://jsfiddle.net/utrdha8f/1/(将您的聊天呼叫更改为 console.log)

我想你要找的就在这个answer

在给定时间刷新,而不是按时间间隔刷新。

function refreshAt(hours, minutes, seconds) {
    var now = new Date();
    var then = new Date();

    if(now.getHours() > hours ||
       (now.getHours() == hours && now.getMinutes() > minutes) ||
        now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
        then.setDate(now.getDate() + 1);
    }
    then.setHours(hours);
    then.setMinutes(minutes);
    then.setSeconds(seconds);

    var timeout = (then.getTime() - now.getTime());
    setTimeout(function() { window.location.reload(true); }, timeout);
}

Then you can add a script tag to call the refreshAt() function.

refreshAt(15,35,0); //Will refresh the page at 3:35pm