Используйте setInterval для повторного вызова блока кода и поместите свой код в некоторую функцию и передайте имя функции в setInterval
первый параметр. Вы можете передавать анонимную функцию вместо создания новой функции, например repeatMe
, но я бы предпочел сделать функцию, чтобы сделать код более читаемым.
function repeatMe(){
$.ajax({
url: 'url',
dataType: 'json',
cache: true,
timeout: 30000,
success: function(data) {
//$('#output ul').append('The feed loads fine');
$('#output ul').empty();
$.each(data.posts, function(i,data){
$('#output ul').append('
'+data.title+'
'+data.text+'
');
});
},
error: function(){
$('#output ul').append('Error');
}
});
}
setInterval(repeatMe, 5000);
Edit It would be better to use setTimeout instead of setInterval in the success to send the next call for update after the first has finished its job. We will also put setTimeout in error to keep the repetive call for update.
function repeatMe(){
$.ajax({
url: 'url',
dataType: 'json',
cache: true,
timeout: 30000,
success: function(data) {
//$('#output ul').append('The feed loads fine');
$('#output ul').empty();
$.each(data.posts, function(i,data){
$('#output ul').append('
'+data.title+'
'+data.text+'
');
setTimeout(repeatMe, 5000);
});
},
error: function(){
$('#output ul').append('Error');
setTimeout(repeatMe, 5000);
}
});
}