1

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)

1
  • Your code works just fine. You only log the array after the first iteration, not each. Commented Aug 13, 2016 at 19:07

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Doh! Instead of adding it to the inner html, could I return students? Ie: return students; To make use of where ever needed.
You sure could, the world is your oyster! Or in this case, object.
Nice! Checkout my edit unfortunately it still just returns one object within the array.
Does this solve your problem? Your recursive function was fine all along, doubt there's a dude on this site ain't done it at some point. It's probably simpler and cleaner - more maintainable - if you handle what you can directly from within your recursive function.
@Nuncy yeah dude. much appreciated, thank you for your time. There's still some problems with my inner code that stops the iteration at 2 objects. But that's on me.
0

Right now it creates one object within the array, but stops.

The issue is console.log(students) is called once outside of recursive function calls. Include console.log(students) within recursive function

function getStudents() {
  var student = {};
    student.name = 'example name';
  student.id = 1;
  students.push(student);
  console.log(students);
  // set recruive
  setTimeout(getStudents, 5000);
}

jsfiddle https://jsfiddle.net/88r0rj8n/3/

14 Comments

Makes sense. Would a return function be appropriate here? I updated my OP, please check it out.
@Modelesq return what value? Where would value be returned to? Is setTimeout cleared?
The array of students. If I wanted to call var studentList = getStudents(); and have the array constantly update.
What do you mean by "constantly available"? students array should currently be available later in javascript by referencing students
the students array is just available within one module. If i wanted to use the function elsewhere and invoke getStudents() is what I mean. I feel like returning a value makes sense.
|
0

You're only logging it once after the first call. If you move the console.log inside the function, it will log the array increasing by one element every 5 seconds

3 Comments

Hmm if i wanted to retrieve the students array, would return work?
it already works, you don't need to return the students array.
If I want to be able to call getStudents(); in other modules, I'd like to be able to return the students array. Yes console.log() works within the function, but I want to be able to return the students array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.