I would like to sum two numbers but when I want to display the result of these two values, I have an error message: NaN
? :S
By looking on this page:
Why do I get NaN from I function in JavaScript
If I understand correctly, I have a variable that is empty?
I don't see what is blocking?
let ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElementsec2 = document.getElementById('value1');
let stockPriceElementsec3 = document.getElementById('value2');
let lastPrice = null
let stockObject = null;
let val1 = null;
let val2 = null;
let sum = null;
ws.onmessage = (event) => {
stockObject = JSON.parse(event.data);
};
setTimeout(() => {
if (stockObject === null) {
return;
}
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElementsec2.innerText = price;
stockPriceElementsec2.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';
lastPrice = price;
stockObject = null;
//console.log("Element 1 => " + lastPrice);
val1 = lastPrice;
console.log("Element 1 => " + val1);
}, 2000);
setTimeout(() => {
if (stockObject === null) {
return;
}
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElementsec3.innerText = price;
stockPriceElementsec3.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? '#AAFF00' : 'red';
lastPrice = price;
stockObject = null;
//console.log("Element 2 => " + lastPrice);
val2 = lastPrice;
console.log("Element 2 => " + val2);
}, 3000);
sum = document.getElementById("result").innerHTML = (parseInt(val1) + parseInt(val2));
console.log(sum);
...
<div class="container ">
<div class="row">
<br /><br />
<div id="no-more-tables">
<table class="col-md-12 table-bordered table-striped table-condensed cf ">
<thead class="cf">
<tr>
<th>Current course</th>
<th class="numeric w7 text-center">Value 1</th>
<th class="numeric w7 text-center">Value 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>BTC</td>
<td class="numeric"><span id="value1"></span></td>
<td class="numeric"><span id="value2"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<br />
<p>Sum : <span id="result"></span></p>