如何计算自最近一次块以来经过的时间(通过blockchain.info的api)?

时间:2015-03-25 00:59:13

标签: javascript bitcoin blockchain

我设法让websocket连接正常工作,并且正在接收来自ping_blockblocks_sub的数据。但是,我很难计算从blockchain.info的api收到的当前日期和阻止日期之间的差异。任何人都可以帮助使用代码来计算自最近一次阻止以来经过了多长时间?

另外,如何保持连接打开以便更新innerHTML对象?

任何建议都将不胜感激。感谢。

<script language="javascript" type="text/javascript">

var wsUri = "wss://ws.blockchain.info/inv";
var output;

function init()
{
    output = document.getElementById("output");
    initWebSocket();
}

function initWebSocket()
{
    //  init blockchain websocket (activity, blocks)
    var blockchain = new WebSocket('wss://ws.blockchain.info/inv');

    blockchain.onerror = function (error){ console.log('connection.onerror',error); };

    blockchain.onopen = function () 
    {
        writeToScreen("Connection to blockchain.info succesful.");
        blockchain.send( JSON.stringify( {"op":"ping_block"} ) );
        blockchain.send( JSON.stringify( {"op":"blocks_sub"} ) );       //  subscribe to new blocks
    };

    blockchain.onmessage = function (message) 
    {
        var response = JSON.parse(message.data);

        var date = new Date(0);
        date.setUTCSeconds( response.x.time );

        if( response.op == "utx")
        {
            var amount = 0;

            for(var i=0;i<response.x.out.length;i++) 
                amount += response.x.out[i].value;

            //  amount is in satoshi
            //  1 BTC = 100,000,000 Satoshi 


([url='https://en.bitcoin.it/wiki/activity)']https://en.bitcoin.it/wiki/activity)[/url]
            response.amount = amount / 100000000;
            response.type = TYPE_TRANSACTION;
            response.index = index++;
            response.date = date;
        }
        else if( response.op == "block" )
        {
            response.type = TYPE_BLOCK;

            response.date = date;

        }

        if( DEBUG ) 
            console.log( response.op, response );

        response.date = date;

        writeToScreen('<span style="color: blue;">Most recent block found      
on: </span>' + response.date);

    };
}


function writeToScreen(message)
{
    var pre = document.createElement("p");
    pre.innerHTML = message;
    output.appendChild(pre);
}

//  constants
var TYPE_TRANSACTION = "transaction";
var TYPE_TRADE = "trade";
var TYPE_BLOCK = "block";
var MINUTE = 1000*60;
var HOUR = MINUTE*60;
var MIN_MINUTES = 1;
var MAX_MINUTES = 10;
var DEBUG = true;
var activity = [];
var index = 0;

 window.addEventListener("load", init, false);

0 个答案:

没有答案