如何连续5秒钟连续拨打ajax电话 [英] how to make ajax calls continuously for 5 seconds once
问题描述
如何连续5秒钟进行一次ajax调用.
How to make ajax calls continuously for 5 seconds once.
我已经使用了setTimeout
,如下所示,
I have used setTimeout
like below,
setTimeout(function()
{
someFn();
}, 200);
但是它使用更多的数据库连接.谁能告诉我一种有效的方法来连续调用一次函数5秒钟.
But it use more db connection. Can anyone tell me an effective way to call a function continuously for 5 seconds once.
我在setTimeout或setInterval内部使用的函数将用于将值更新到数据库.因此这将增加数据库连接.并导致丢失的数据库连接错误.所以我需要一些不会增加数据库连接的东西
Function that i use inside setTimeout or setInterval will be used to update values to database.hence this will increase db connections. and result in lost db connection error.so i need something that will not increase db connections
我正在使用以下代码
push_notification('<?php echo $user_details1[0]['id']; ?>');
setInterval(function()
{
push_notification('<?php echo $user_details1[0]['id']; ?>');
}, 10000);
function push_notification(driver_id)
{
var dataS = "&type=1&driver_id="+driver_id;
var SrcPath = "<?php echo URL_BASE; ?>";
var response;
$.ajax
({
type: "POST",
url: SrcPath+"driver/adminpushnotification/1",
data: dataS,
cache: false,
dataType: 'html',
success: function(response)
{
//some Functionality
}
});
}
推荐答案
这将每interval
毫秒执行一次fn
,并且在duration
毫秒后将停止执行.
This will execute fn
every interval
milliseconds, and after duration
milliseconds it will stop.
var duration = 5000,
interval = 200,
intervalTimer;
intervalTimer = setInterval(function() {
fn();
}, interval);
setTimeout(function() {
clearInterval(intervalTimer);
}, duration);
更新
但是,如果您是在间隔回调中发出ajax请求,并且想要阻止在先前的请求仍处于未决状态时发出新的请求(因为我现在正在解释您的问题),则可以检查状态提出新请求之前,先处理之前的请求.如果您使用的是jQuery,它可能看起来像这样:
Update
However, if you're making ajax requests within the interval callback, and want to prevent a new request from being made while a previous request is still pending (as I'm now interpreting your question), you can check the status of the previous request before making a new one. Providing you're using jQuery, it could look something like this:
var duration = 5000,
interval = 200,
xhrPending = false,
intervalTimer;
intervalTimer = setInterval(function() {
if (xhrPending) return;
$.ajax(...).done(function() {
xhrPending = false;
});
xhrPending = true;
}, interval);
setTimeout(function() {
clearInterval(intervalTimer);
}, duration);
这篇关于如何连续5秒钟连续拨打ajax电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!