简体   繁体   中英

How can I run jQuery load() request each n seconds?

I have following code

$('document').ready(function() {
  reload(); 
}); 

function reload() {
  $('div#info').load('http://somesite.ru/script.php');
  setInterval(reload(), 10000);   
}

but seems like method reload() runs too fast. Firefox shows me message, about jquery.min.js is sems to busy. How can I make part of page refresh one time for each 10 seconds?

You should remove the () , also put the setInterval function outside the context of the reload function.

function reload() {
   $('#info').load('http://somesite.ru/script.php');
}
$(document).ready(function() {
   setInterval(reload, 10000);   
}); 

Replace:

setInterval(reload(), 10000);   

with:

setInterval(reload, 10000);   

Use setTimeout() instead it is safe and performance wise good than the setInterval() to fulfill your requirement.

var time= setTimeout(reload,1000);

after checking certain conditions in the reload() method call the setTimeout inside it again

function reload()
{
 /// your logic
setTimeout(reload,1000);
}

use the above variable to destroy the interval whenever you don't want to reload anymore

clearTimout(time);
       Refer: http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval

     setInterval(function(){reload();},10000);

Another way is just use

$('document').ready(function() {
  setInterval(function() { 
    $('div#info').load('http://somesite.ru/script.php'); 
  }, 10000);
});

All works fine. Thanks a lot for your answers.

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