无法理解javascript中的回调。请检查

时间:2018-02-06 14:02:51

标签: javascript callback

我编写了代码来测试回调。但我直接得到了两个电话的答案5。我分别需要2和5。如何实现它。

var count = 0;

function increment(number, callback) {
    count = count + number;
    setTimeout(callback, 10000);

}

var done = function() {
    console.log(`count is :${count}`);
};
increment(2, done);
increment(3, done);

1 个答案:

答案 0 :(得分:1)

您已立即将号码添加到count ,然后安排回调以显示结果。这意味着只要两次致电incrementcount就是5。然后20和50秒后,显示。您可以看到,如果我们在通话后console.log(计数:$ {count} );两次通话后(我已将超时时间降低到2秒和5秒):



var count = 0;

function increment(number, callback) {
  count = count + number;
  setTimeout(callback, 1000);

}

var done = function() {
  console.log(`count is :${count}`);
};
increment(2, done);
increment(3, done);
console.log(`count after calls :${count}`);




相反,您希望在计时器回调中将number添加到count(我已将超时时间降低到2秒和5秒):



var count = 0;

function increment(number, callback) {
  setTimeout(function() {
    // Our timer callback fired, update count
    count += number;
    // Call the main callback
    callback();
  }, 1000);
}

var done = function() {
  console.log(`count is :${count}`);
};
increment(2, done);
increment(3, done);