user5544792 user5544792 - 4 months ago 21
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.


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://');
btcs.onopen = function()
    btcs.send( JSON.stringify( {"op":"unconfirmed_sub"} ) );
btcs.onmessage = function(onmsg)
    var response = JSON.parse(;
    var amount = response.x.out[0].value;
    var calAmount = amount / 100000000;
    $('#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.