Reputation: 141
I want to display some data which comes from my db using jQuery.ajax() (i.e. each one contains a title and a description) and I want this process to be done on a regular basis, say setInterval(func, 5000).
Now what I actually need is a js container (an array, a variable, whatever) in which I can store these items to and using another function, I want them to be displayed every 2 seconds.
So, in other words:
How can I implement this?
Upvotes: 2
Views: 523
Reputation: 23530
var queue = [];
function ajaxCall() {
$.when($.ajax(...)).done(function(data) {
///assuming your data json's outermost structure is an array
while(data[0]) {
queue.push(data.shift());
}
})
}
function publisher() {
var item = queue.shift();
if(item) {
//do your gubbins here
}
}
setInterval(ajaxCall,5000);
setInterval(publisher, 2000);
Upvotes: 2
Reputation: 997
first, set up a container like this one :
<div id="container">
<ul>
</ul>
</div>
then, in your .js :
//step 1. define global Array to hold the values
$(document).ready(function(){
var items = new Array();
//step 3. call the ajax every 5 second
var updateInterval = setInterval(function() {
get_the_data();
//don't forget to empty the array
items = [];
}, 5000);
//step 4. so now, with the data got refresh every 5 second, you just have to append this data into container every 2 second. use the .html method
//logically, in first two times invoke to this method (4 seconds) the container would get same data from array, but in third invocation (at 6 seconds) the container get the fresh one, and so on...
var insertToContainer = setInterval(function() {
for(i=0;i<items.length;i++){
$('#container ul').html('<li>' + items[i] + '</li>')
}
}, 2000);
});
//step 2. set up your ajax call
function get_the_data()
{
$.ajax({
//set your ajax code here...
success:function(data){
//on success put the data into the global array
for(i=0;i<data.length;i++){
items.push(data[i]);
}
}
});
}
I hope this would work for your project. Cheers :-) PS: frankly speaking, I don't know why you wanted such implementation (i mean, 2 different update functions with different interval value), the more simple way is using just one invocation to the ajax call every 2 seconds as long as display it in container using .html , but it's just my opinion, It should be more complex logic behind your app. :-)
Upvotes: 0