javascript ajax setinterval delay

旧巷老猫 提交于 2019-12-04 06:25:24

问题


How can I execute this function immediately, then start the setInterval timer?

Here is my js.

$(document).ready(function(){
        var callAjax = function(){
          $.ajax({
            method:'get',
            url:'apinvs.php',
            dataType:'html',        
            success:function(data){
              $("#main").html(data); } 
          });
        }
                setInterval(callAjax,2500); 
      });

It's executing the function after 2.5 seconds. It leaves the div blank until 2.5 seconds pass, which is what I don't want to happen. :(

I found a Stackoverflow question here but I'm not sure how to apply it with my code (it's using document ready). Thanks for any assistance.


回答1:


Change

setInterval(callAjax,2500); 

to

callAjax();
setInterval(callAjax,2500); 



回答2:


do you mean something like this? or do I get your question wrong?

$(document).ready(function(){
    var callAjax = function(){
      $.ajax({
        method:'get',
        url:'apinvs.php',
        dataType:'html',        
        success:function(data){
          $("#main").html(data);
          setInterval(callAjax,2500); 
        }
      });
    }
  });



回答3:


Nevermind, can't believe it was this simple.

Changed my code to..

$(document).ready(function(){
        var callAjax = function(){
          $.ajax({
            method:'get',
            url:'apinvs.php',
            dataType:'html',        
            success:function(data){
              $("#main").html(data); } 
          });
        }
                setInterval(callAjax,5000); 
                callAjax();
      });

(called the function)

It's working perfectly now.



来源:https://stackoverflow.com/questions/26349876/javascript-ajax-setinterval-delay

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