0

I´m storing some values in an array and print them on an HTML page with Javascript. So far so good. Now I want to use the same data in the array for a data graphic. But I can´t get the array out of the function in which I created the array. I can´t event print it out as I did before from inside the function. This doesn´t seem impossible, but I don´t get it. I tried to define a getter function, but I wasn´t successful. Maybe someone can help me.

By the way, I received the data from a node.js server via Socket.io. On http://jsfiddle.net/dL3Lsx0L/ I reduced the code and strangely it works there, but not in my original code below.

    <script src='//code.jquery.com/jquery-1.7.2.min.js'></script>
    <script src='//localhost:3000/socket.io/socket.io.js'></script>
    <script>

        var socket = io();
        var values_array = new Array();

        socket.on('server2browser', function(data)        // Receive data from server
        {
            fct_values_array(data);   
        });


        function fct_values_array(data)     
        {
             $.each(data, function(i, obj)                // Store received data in array
             {
                 values_array[i] = obj.numbers;      
             });         
             $('#arrayprint_values').text(values_array);  // Print array on HTML - It works.
        }


        $('#printagain').text(values_array);              // Print array again - Doesn´t work.
    </script>
wurstbrotrest
  • 329
  • 1
  • 7
  • 17
  • 2
    The only time that `values_array` is modified is when `fct_values_array` is called. By the time we reach `$('#printagain')...` it hasn't been modified (probably) because `socket.on` is an asynchronous method? What are you trying to achieve? – Ian Clark Nov 16 '14 at 13:07
  • If you use `console.log()` to print the values you'll likely find that the code isn't running in the order that you expect. Printing to two separate html elements doesn't show you the timing. – nnnnnn Nov 16 '14 at 13:07
  • Qantas´ link was very helpful. Yes, it might be a duplicate. I replaced $('#arrayprint_values').text(values_array); with setTimeout(function() { $('#arrayprint_values').text(values_array); }, Math.random() * 1000); – wurstbrotrest Nov 16 '14 at 23:18

1 Answers1

-1

This works for me: Replace

$('#arrayprint_values').text(values_array);

by

setTimeout(function() { 
    $('#arrayprint_values').text(values_array); 
}, Math.random() * 1000);
wurstbrotrest
  • 329
  • 1
  • 7
  • 17