gpt4 book ai didi

jquery - 每 X 分钟使用 AJAX 调用一个文件,直到 Y 时间?

转载 作者:行者123 更新时间:2023-12-01 07:52:35 25 4
gpt4 key购买 nike

我有以下代码

$(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 加载后)它停止(直到页面刷新/更改)?

我正在尝试其中一个答案,但它不起作用。对于 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)

关于jquery - 每 X 分钟使用 AJAX 调用一个文件,直到 Y 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com