Reputation: 4342
I am trying to load content from 2 different URLS but at different intervals. Ideally I would like to load one url wait 10 seconds load the other and repeat the over and over. This is what I have but its not working correctly. Its constantly loading the urls rapidly back and forth so fast I cant read the content
setInterval(function(){
$('#ticker').load('misc.php?users=10');
}, 10000);
setInterval(function(){
$('#ticker').load('misc.php?news=10');
}, 20000);
Upvotes: 0
Views: 151
Reputation: 3219
Are you setting a timeout because you're wanting to ensure that the first URL gets read first, and the second URL gets read second, in that order? If that's the case, I might suggest a new pattern, like so...
(function($) {
var fn1 = function () {
$.ajax({
url: 'misc.php?users=10'
}).done(function (data) {
// update #ticker html with new user data
}).always(function () {
fn2(); // whether we succeed or not, we move on to fn2
});
}
, fn2 = function () {
$.ajax({
url: 'misc.php?news=10'
}).done(function (data) {
// update #ticker html with new news data
}).always(function () {
fn1(); // whether success or failure we start over on fn1
});
};
// ... somewhere down the line ...
$('#ticker').on('load', fn1); // start polling
})(jQuery);
What we're doing here is making asynchronous calls in a somewhat synchronous fashion, without the need of messy timeout or interval calls. This maintains the order of your URLs without them overlapping or getting tangled up in AJAX requests. And as soon as one finishes, the other begins again, constantly polling until we change to a different page.
Upvotes: 0
Reputation: 78991
I have a better suggestion
var links = ['misc.php?users=10', 'misc.php?news=10'];
var pointer = 0;
setInterval(function() {
$("#ticker").load(links[pointer++ % links.length]);
}, '10000');
Upvotes: 1
Reputation: 2311
You can try using .load
's callback function.
$('#ticker').load('misc.php?users=10', function(){
setInterval( function(){
$('#ticker').load('misc.php?news=10');
}, 10000 );
});
Upvotes: 0