Home Forums Chart Support Can not use variables outside the function

Can not use variables outside the function

Viewing 4 posts - 1 through 4 (of 4 total)
  • #24218

    This code is working fine but I can not use variables
    S and A outside the function as global variables ! Why,
    in spite of definition for global variables inside the
    function, I have in console the error message: S and A not
    defined ?

    var Xa = 0
    var updateInterval = 10;
    var updateChart = function () {

    S = 35;
    A = Math.sin(Xa * Math.PI / 180);
    dps.push({ x:Xa ,y:A });
    Xa++;

    while(dps.length >= 720){
    dps.shift();}

    chart.render();
    };
    setInterval(function(){updateChart()}, updateInterval);

    console.log (S);
    console.log (A);

    #24228

    Sorry, it is not the question for CanvasJS ! It is my
    ignorance in JavaScript.Problem solved with JavaScript Closures.

    #24230

    @sepetar,

    Variable S and A gets value and goes to global scope inside updateChart method, which gets executed after 10ms (based on the value of updateInterval). But you are consoling the values is outside the method – which gets executed first. Consoling S and A after the first execution of updateChart method should work fine in this case.

    Example:

    var updateChart = function () {
        S = 35;
        A = Math.sin(Xa * Math.PI / 180);
    }
    setInterval(function(){
        updateChart();
        consoleValues();
    }, 1000);
    
    function consoleValues(){
      console.log(S); //Still accessible outside updateChart method
      console.log(A);
    }


    Vishwas R
    Team CanvasJS

    #24237

    Thank You Vishwas R. – it is helping me a lot.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.