简体   繁体   English

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

[英]unable to understand callback in javascript. please check

I have written my code to test the callback . 我已经编写了代码来测试回调。 but i am getting answer 5 directly for the two calls. 但我直接得到两个电话的答案5。 I need 2 and 5 respectively. 我分别需要2和5。 How to achieve it. 如何实现。

var count = 0; 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);

You're adding the number to count immediately , then scheduling a callback to show the result. 您要添加要立即 count的数字,然后安排回调以显示结果。 That means as soon as the two calls to increment run, count is 5 . 这意味着两个调用increment运行时, count5 Then 20 and 50 seconds later, that is shown. 然后显示20和50秒。 You can see that if we do console.log( count after calls :${count} ); 您可以看到,如果我们执行console.log(调用后计数:$ {count} ); after the two calls (I've lowered the timeouts to 2 and 5 seconds): 在两次通话之后(我将超时时间降低到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}`); 

Instead, you'll want to add number to count in the timer callback (I've lowered the timeouts to 2 and 5 seconds): 相反,您需要添加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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM