What is logic behind this code?

I found this code in one of free sample. I am trying to figure it out how it is working.
This code is for rendering dynamic graph

HTML Code

     <div>
           <div id="mychart">
           </div>
      </div>

Javascript code

   var updateInterval = 30;
   var plot = $.plot($("#mychart"), [getRandomData()], options);

   function update() {
                plot.setData([getRandomData()]);
                plot.draw();
                setTimeout(update, updateInterval);
            }
   update();

Javascript method - getRandomData

          var data = [];
          var totalPoints = 250;   //I want to know what is this 250????

          function getRandomData() {
            if (data.length > 0) data = data.slice(1);
            // do a random walk
            while (data.length < totalPoints) {
                var prev = data.length > 0 ? data[data.length - 1] : 50;
                var y = prev + Math.random() * 10 - 5;
                if (y < 0) y = 0;
                if (y > 100) y = 100;
                data.push(y);
            }
            // zip the generated y values with the x values
            var res = [];
            for (var i = 0; i < data.length; ++i) res.push([i, data[i]])
            return res;
        }

Can somebody help me to understand this code? I want to know why they used totalPoints=250??

Above code is rendering dynamic graph as shown below

HI CodeMaker welcome to the forum

The “250” is used in the for loop that assigns random values.

In this case “250” is only being used to determine a good number of data points to demonstrate an example of how the graph will look.

In real use, the totalPoints value would most likely not be hard coded, but would be the count / length of an array of data values.
And instead of random y values the y values would come from the data array.

Or even more likely, a modified version of the getRandomData function would not be used at all and an array of “real” data would be used in its place.

That is, the getRandomData function is creating an array for the graph to use in the absence of a “real” array.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.