我正在研究JavaScript并且有一个任务是编写一个公共函数来检查是否进行了异步调用,但是响应仍处于未决状态(即进程是"正在运行")。如果流程正在进行,则需要返回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
});
答案 0 :(得分:1)
在run()中,将对象上的标志设置为true(通过this.running = true;
)isRunning()方法返回。
完成运行后,将其设置为false。
答案 1 :(得分:1)
以下是编码方式:
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
});