gpt4 book ai didi

javascript - 如何检查回调是否待处理?

转载 作者:行者123 更新时间:2023-12-02 14:13:55 26 4
gpt4 key购买 nike

我正在学习 JavaScript,并有任务编写一个公共(public)函数来检查是否进行了异步调用,但响应仍处于待处理状态(即进程正在“运行”)。如果该过程正在进行,则需要返回 true;如果没有,则需要返回 false

function Machine() {
function onReady() {
alert( 'ready!' );
}
this.setOnReady = function(newOnReady) {
onReady = newOnReady;
};
this.run = function() {
setTimeout(function() {
onReady();
}, 10000);
};
}

var machine = new Machine();
alert('before the run: ' + machine.isRunning()); // before: false
machine.run();
alert('is running: ' + machine.isRunning()); // is running: true
machine.setOnReady(function() {
alert("after: " + machine.isRunning()); // after: false
});

最佳答案

以下是编码方法:

function Machine() {
// add this private variable
var isRunning = false;
function onReady() {
alert( 'ready!' );
}
this.setOnReady = function(newOnReady) {
onReady = newOnReady;
};
this.run = function() {
isRunning = true; // set flag
setTimeout(function() {
isRunning = false; //clear flag
onReady();
}, 2000); // 2 seconds, I don't have patience!
};
// Add this method:
this.isRunning = function() {
return isRunning;
}
}

var machine = new Machine();
console.log('before the run: ' + machine.isRunning()); // before: false
machine.run();
console.log('is running: ' + machine.isRunning()); // is running: true
machine.setOnReady(function() {
console.log("after: " + machine.isRunning()); // after: false
});

关于javascript - 如何检查回调是否待处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com