lastbalance永远不会被定义,因此getBalance函数永远不会做它应该做的事情。我认为这可能是异步性的问题,但是只有在第一个时间间隔之前是这样,对吧?有任何想法吗?

var lastbalance;
getBalance = function (lastbalance, callback){
  btcclient.getBalance('*', 0, function(err, balance) {
    if (err) return console.log(err);
    if (lastbalance != balance || typeof lastbalance == 'undefined'){
      console.log('Last Balance:' + lastbalance);
      var lastbalance = balance;
      updateCauses();
    }
    console.log('Balance:', balance);


    if (typeof callback=='function') callback();

  });
};

setInterval(getBalance, 2000, lastbalance);

最佳答案

两个问题。

1 .: 。您已将lastbalance定义为函数参数...,这在函数的上下文中创建了另一个lastbalance变量...取代了在外部范围中声明的变量。

var lastbalance; // your outer variable
getBalance = function (lastbalance, callback) { // weeeee, another lastbalance
    btcclient.getBalance('*', 0, function (err, balance) {
        if (err) return console.log(err);
        if (lastbalance != balance || typeof lastbalance == 'undefined') {
            console.log('Last Balance:' + lastbalance);
            var lastbalance = balance;
            updateCauses();
        }
        console.log('Balance:', balance);
        if (typeof callback == 'function') callback();
    });
};

setInterval(getBalance, 2000, lastbalance); //passing lastbalance by value

2 .: 您使用var在函数中声明了另一个lastbalance。不要那样做它导致了上述相同的问题。
var lastbalance; // your outer variable
getBalance = function (lastbalance, callback) {
    btcclient.getBalance('*', 0, function (err, balance) {
        if (err) return console.log(err);
        if (lastbalance != balance || typeof lastbalance == 'undefined') {
            console.log('Last Balance:' + lastbalance);
            var lastbalance = balance; // here you create a local lastbalance.
                                       // remove the var keyword to refer to
                                       // the original lastbalance
            updateCauses();
        }
        console.log('Balance:', balance);
        if (typeof callback == 'function') callback();

    });
};

setInterval(getBalance, 2000, lastbalance);

最后,您的代码应如下所示:
var lastbalance;
getBalance = function (callback) { // remove parameter
    btcclient.getBalance('*', 0, function (err, balance) {
        if (err) return console.log(err);
        if (lastbalance != balance || typeof lastbalance == 'undefined') {
            console.log('Last Balance:' + lastbalance);
             lastbalance = balance; // remove var
            updateCauses();
        }
        console.log('Balance:', balance);
        if (typeof callback == 'function') callback();
    });
};

setInterval(getBalance, 2000); // remove argument

07-28 07:13