You must be logged in to post your query.
Home › Forums › Chart Support › Can not use variables outside the function
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);
Sorry, it is not the question for CanvasJS ! It is my ignorance in JavaScript.Problem solved with JavaScript Closures.
@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
Thank You Vishwas R. – it is helping me a lot.
You must be logged in to reply to this topic. Login/Register