how to make ajax calls continuously for 5 seconds once

好久不见. 提交于 2019-12-23 03:15:19

问题


How to make ajax calls continuously for 5 seconds once.

I have used setTimeout like below,

setTimeout(function()
{
    someFn();
}, 200);

But it use more db connection. Can anyone tell me an effective way to call a function continuously for 5 seconds once.

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

i am using below code

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
        }
    });
}

回答1:


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

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



回答2:


This will execute for every 3 seconds.

  <button onclick="setInterval(function(){alert('Hello')},3000);">Click Me</button>



回答3:


A hacky way would be to call it every 200 ms 25 times, resulting in stopping after 5 seconds (25 calls).

This will call the function ajaxCall() 25 times before clearing the interval after 5 seconds.

var ajaxInterval = setInterval(function(){AjaxTimer()},200);
var counter = 1;

function AjaxTimer()
{
  if(counter > 25) {
    clearInterval(ajaxInterval );
  } else {
    ajaxCall();
    counter++;
  }
}


来源:https://stackoverflow.com/questions/31759545/how-to-make-ajax-calls-continuously-for-5-seconds-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!