Modelesq Modelesq - 3 months ago 27
Javascript Question

Using a recursive function to dynamically update an array

I'm having a hard time getting my array of objects to display and dynamically update.

The expected output would be an array of student objects, that update every 5 seconds. Meaning A new student obj will be added to the array.

This is my function:

var students = [];

function getStudents() {
var student = {};
student.name = 'example name';
student.id = 1;
students.push(student);
// recursive
setTimeout(getStudents, 5000);
return students;
}

getStudents();


Right now it creates one object within the array, but stops. How can I make this work? What am I doing wrong?

Fiddle here to illustrate.

(Thank you for your help in advance)

Answer

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();