我编写了代码来测试回调。但我直接得到了两个电话的答案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);
答案 0 :(得分:1)
您已立即将号码添加到count
,然后安排回调以显示结果。这意味着只要两次致电increment
,count
就是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);