0

I currently have a function in my javascript in which I am trying to constantly push elements into an array. It looks something like this:

setInterval(function () {
    var currentdate = new Date(); 
    var datetime = currentdate.getFullYear() + "-" +
                   (currentdate.getMonth() + 1) + "-" +
                   currentdate.getDate();

    var arrayofdates = [];
    arrayofdates.push(datetime);
    document.getElementById("demo").innerHTML = arrayofdates;

    var a = (Math.random() * 100) + 1;
    var b = (Math.random() * 100) + 1;
    var c = (Math.random() * 100) + 1;

    chart.load({
        columns: [
            ['x', datetime],
            ['data1', a],
            ['data2', b],
            ['data3', c]
        ]
    });
}, 1000);

For some reason, the arrayofdates is only stuck in one. I have checked the properties of the arraylist and even if the string is already in the list, it should still add onto the list. In this case, I am getting a string similar to 2015-08-11, but I expect the arraylist to keep on adding 2015-08-11 after every second. What am I doing wrong?? Thanks!

2
  • 2
    That keeps happening because you keep re-declare your array every single time. Commented Aug 12, 2015 at 1:03
  • @Isuckatprogramming—you mean re–initialising every time. ;-) Commented Aug 12, 2015 at 1:19

1 Answer 1

4

Your 'var arrayofdates' variable is re-created each time when the setInterval callback fires. Try declare it outside the setInterval()

Sign up to request clarification or add additional context in comments.

1 Comment

Can't believe I missed that. One of the dumbest errors I've made! Thanks a lot!

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.