One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call.
Take a look at the example code here.
myObj = {};
var output = '';
var items = '';
myObj.displayItems = function() {
console.log('displayItems executed');
output = '';
$.each(items, function(index, val) {
output += '<li>' + val.player.firstName + ' ' + val.player.lastName + '</li>';
});
$('#content').html(output);
};
$(document).ready(function() {
(function loadData() {
setTimeout(function() {
console.log('loadData executed....');
return $.ajax({
url: '//jsbin.com/xinixa/1.json',
type: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
items = data.apiResults[0].league.season.draft.rounds[0].picks;
loadData();
myObj.displayItems();
},
});
}, 3000);
})();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="content"></div>
</body>
</html>
Every time I try to put the setTimeout call inside the function during refactoring, I encounter errors. Making the function non-self-executing also leads to errors.