user5544792 user5544792 - 6 months ago 42
jQuery Question

Getting total from javascript websocket

I have a program that displays bitcoin transactions through websockets, and the amount uses JSON as well.

I send it through to a div in the html with the javascript. With this:

$('#messages').prepend("<p>" + calAmount + "</p>");


Since it continues to make new paragraph elements, how can I add it up while its in the javascript or the html.

I thought of making a loop to add it, but since it is one variable it doesn't seem to work.

I'm working towards a "total" thing to display total transaction amounts. So in a 15 minute period it will display the total amount of bitcoin sent.

https://jsfiddle.net/Kryometric/7x55uhm9/1/

Answer

Hard to say exactly what you're asking for, but it sounds like you just need a second global variable (or btcs-level variable as in your fiddle) to handle the running total.

var total=0;
var btcs = new WebSocket('wss://ws.blockchain.info/inv');
btcs.onopen = function()
{
    btcs.send( JSON.stringify( {"op":"unconfirmed_sub"} ) );
};
btcs.onmessage = function(onmsg)
{
    var response = JSON.parse(onmsg.data);
    var amount = response.x.out[0].value;
    var calAmount = amount / 100000000;
    total+=calAmount;
    $('#messages').prepend("<p>" + calAmount + "</p>");  
}

Because total persists outside the onmessage handler, you can do whatever you want with it after it has been updated within the handler at any time.