2015-01-09 47 views
1

我有以下代码每隔X分钟用AJAX调用一次文件直到Y时间?

$(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,我是一个noob,我是否正确地做了这件事?

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++; 

    }); 
+2

你怎么样,每次循环,您可以添加拍摄,直到它等于10分钟的时间?然后,你可以关闭它。 – SirPython

回答

2

三个简单的步骤:

  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)

+0

除非用户使用JavaScript代码混淆,否则此解决方案可以完美工作。第二个(也是更安全的)选项:打开一个PHP会话,记录来自该用户会话的呼叫数量,当他们达到某个数字时忽略请求 –

+0

我试过这个,但它似乎没有做任何事情。我会用我的代码更新OP,我是否正确? – Drennon

+0

它不起作用 - 仍然持续加载并不停止。 :(是aux设置为除clearInterval以外的任何其他内容吗? – Drennon

1

我觉得你在找什么在这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); 
} 

然后你就可以添加一个script标签调用refreshAt()函数。

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