简体   繁体   中英

Setinterval Firing Multiple Times at once

I have a app where I want to check a URL every 5 seconds, so I use following code:

<script>

function checknow()
{

  $.get( "https://example.com", function(data) {
  console.log(data);
  });


}

setInterval(function(){
    
    console.log("time started...");
    checknow();
    
    
}, 5000); 

</script>

Its working fine in my one computer, but in another computer, it checks every 5 seconds, but after 1 minute.. it's not calling function for 30 seconds and suddenly calls the function 6 times at once. Since it happens randomly I am unable to debug. I have 50 clients and only around 5 clients reporting this issue.

Is there any problem with setInterval , or is there any alternatives?

Ps: webpage is in foreground and active when I check this.

You can use setTimeout to better control the time between requests.

function checknow(){
  $.get("https://example.com", function(data) {
      console.log(data);
      setTimeout(checknow, 5000);
  });
}
checknow();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM