javascript - 我的回调有什么问题?

标签 javascript callback

我正在尝试学习回调并想知道我在这里做错了什么,因为我希望在 4 秒后收到一条消息:

I've tried to fire but one of the funcs isn't finished yet

8 秒后紧接着是另一条消息:

I waited for the two functions to finish and now I've fired

相反,我只是得到:

I waited for the two functions to finish and now I've fired

两次,分别在 4 秒后和 8 秒后。

var cbvarone = false;
var cbvartwo = false;

var whenOthersFinished = function() {
    if (cbvartwo && cbvartwo) {
    console.log("I waited for the two functions to finish and now I've fired");
    }
    else {
    console.log("I've tried to fire but one of the funcs isn't finished yet");
    }
};

var firstFunc = function(cb) {
    setTimeout(function(){cbvarone = true; cb();}, 8000);
};

var secondFunc = function(cb) {
    setTimeout(function(){cbvartwo = true; cb();}, 4000);
};

firstFunc(whenOthersFinished);
secondFunc(whenOthersFinished);

最佳答案

在你的函数中:

var whenOthersFinished = function() {
    if (cbvartwo && cbvartwo) {
    console.log("I waited for the two functions to finish and now I've fired");
    }
    else {
    console.log("I've tried to fire but one of the funcs isn't finished yet");
    }
};

你的 if 语句是:

if (cbvartwo && cbvartwo)

将其更改为:

if (cbvarone && cbvartwo)

一切都应该没问题。我已验证并且您的代码在更改后按预期工作

关于javascript - 我的回调有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31617557/

相关文章:

javascript - 使用数组和循环每隔几秒更改一次标题

javascript - 如何检查 textarea (tinymce) 是否只包含空格?

javascript - Chrome 扩展程序在当前文档中植入图像

javascript - 使用 Protractor 使用部分文本来控制重定向

你不懂 JS 的 javascript 模块模式

Javascript 将参数传递给回调函数

javascript - JQuery 检查必填字段

javascript - 通过多个回调优雅地传递 "click event"

c - c 中的 TimerProc 不工作?

c++ - 如何改进c风格的函数回调系统?