Again, I added the <div id="test"> element to collect the output.
<div id="test">
</div>
I created some arrays so that I had data to work with.
// Here's an array of students we can add for test purposes...
//
var arrStudents = [ "Rita", "Sue", "And", "Bob", "too" ];
var arrIDs = [ 123, 234, 345, 456, 567 ];
// We can populate 5 students with the above data, this will
// keep track of the number of students added.
//
var intStudents = 0;
var students = [];
I created the function updateTest() which is recursively called by the getStudents() function:
function updateTest() {
var a;
document.getElementById('test').innerHTML = "";
for (a = 0; a < students.length; a++) {
// Append the output to innerHTML
//
document.getElementById('test').innerHTML +=
a.toString() +
": Student name: " + students[a].name +
", ID: " + students[a].id + "<br />";
}
}
Now call updateTest() each time the getStudents() function is called, you'll see the list of students grow.
function getStudents() {
var student = {};
if (intStudents < 5) {
// Add one of the students from our arrays.
//
student.name = arrStudents[intStudents];
student.id = arrIDs[intStudents];
}
else {
// Just keep adding this when we run out of students.
//
// We can still use intStudents to generate a unique
// name and id.
//
student.name = 'example name ' + intStudents.toString();
student.id = intStudents;
}
intStudents++;
students.push(student);
// recursive
setTimeout(getStudents, 5000);
// call updateTest() each time to update the div...
//
updateTest();
}
getStudents();