0

I want to populate two arrays in javascript to simulate timely updating chart. For this I want two charts to be populate.

var array1 = [1,2,3,...] //time in seconds var array2 = [10,15,12,...] //any random number

Each element should be pushed to the arrays with one second of interval.

Tried this but arrays are not getting updated as I want.

var time = [];
var value = [];

$(document).ready(function() {
    update();
});

    function update() {
      var index = 0;
      setTimeout(function () {
        index++;
        time.push(index);
        value.push(Math.random() * (0 - 200));
        console.log(time)
        console.log(value)
        update();
      }, 1000);
    }
3
  • What happens instead? Commented Dec 18, 2014 at 8:13
  • Silly mistake of putting index inside the function. Updated it correctly. Commented Dec 18, 2014 at 8:16
  • 2
    don't fix your question now specially if it was the source of the main mistake. Otherwise the Answers will look silly. Commented Dec 18, 2014 at 8:23

3 Answers 3

3

fiddle

var index = 0 It's not getting updated cause at every iteration you're resetting it to 0. Move it outside of your update() fn

So try like:

var index = 0 ; // Outside the update fn scope
var time = [];
var value = [];

$(document).ready( update );

function update() {
    setTimeout(function () {
        time.push(++index);
        value.push( ~~(Math.random() * 200 ) + 1);
        console.log(time)
        console.log(value)
        update();
    }, 1000);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was suspecting I wasn't reading the same thing ... let's clear up comments
1

You should move var index = 0; outside of update function.

var time = [];
var value = [];

$(document).ready(function() {
  update();
});
var index = 0;

function update() {

  setTimeout(function() {
    index++;
    time.push(index);
    value.push(Math.floor(Math.random() * 200));
    console.log(time)
    console.log(value)
    update();
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

1

You're after setInterval (almost same usage as setTimeout you're using).

Difference is, setTimeout runs the function once after the specified timeout, while setInterval runs repeatedly.

Also check out clearInterval (to be run on the return value of setInterval) which stops the execution of the function.

// to start
var interval = setInterval(function () { /* ... */ }, 1000);

// to stop
clearInterval(interval);

You also no longer need to invoke update() inside itself after switching functions.

Comments

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.