Use setInterval to call the code block again and put your code in some function and first pass the function name to the setInterval parameter. You can pass an anonymous function instead of creating a new function like repeatMe , but I would prefer to make a function to make the code more readable.
function repeatMe(){ $.ajax({ url: 'url', dataType: 'json', cache: true, timeout: 30000, success: function(data) { // $('#output ul').append('<li>The feed loads fine'); $('#output ul').empty(); $.each(data.posts, function(i,data){ $('#output ul').append('<li><a href="'+data.image+'"><img class="thumb" src="'+data.image+'" alt="" /></a><h3>'+data.title+'</h3><p>'+data.text+'</p></li>'); }); }, error: function(){ $('#output ul').append('<li>Error'); } }); } setInterval(repeatMe, 5000);
Change It is better to use setTimeout instead of setInterval in success to send the next update call after the first has completed its job. We will also put setTimeout in error to save the callback for the update.
function repeatMe(){ $.ajax({ url: 'url', dataType: 'json', cache: true, timeout: 30000, success: function(data) { // $('#output ul').append('<li>The feed loads fine'); $('#output ul').empty(); $.each(data.posts, function(i,data){ $('#output ul').append('<li><a href="'+data.image+'"><img class="thumb" src="'+data.image+'" alt="" /></a><h3>'+data.title+'</h3><p>'+data.text+'</p></li>'); setTimeout(repeatMe, 5000); }); }, error: function(){ $('#output ul').append('<li>Error'); setTimeout(repeatMe, 5000); } }); }
source share