這可能是一個非常愚蠢的問題,我對javascript幾乎一無所知。當我在其中一個類函式中更改物件的變數時,它不會改變。“我真的不能很好地解釋事情..” 在這種情況下,當我嘗試“關閉”這個類時,this.Status only = Off 在 Stop 函式的范圍內。
注意:我使用的是 Node.js
代碼
module.exports = class Sniper {
constructor() {
this.Status = 'Off'
}
async start() {
this.Status = 'On'
while (this.Status == 'On') {
console.log(this.Status)
}
}
stop() {
//When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
this.Status = 'Off'
console.log(this.Status)
}
}
我該如何解決?
uj5u.com熱心網友回復:
您創建了一個無限回圈。如果你將一個函式標記為async它仍然是同步的,但你可以Promises在其中啟動和等待。
這個邏輯不起作用,不確定你到底想要什么,但你不能從它的范圍之外停止一個同步的無限 while 回圈。
我能想象的最接近的是這樣的:
class Sniper {
constructor() {
this.Status = 'Off'
}
async start() {
this.Status = 'On'
while (this.Status === 'On') {
// Lets just give a bit of time for the engine to run other code
await new Promise(resolve=>setTimeout(resolve,10));
console.log(this.Status)
}
}
stop() {
//When I try to change this value, it only changes in this scope, so the while loop in the start function keeps running
this.Status = 'Off'
console.log(this.Status)
}
}
const sniper = new Sniper();
sniper.start();
setTimeout(()=>{
sniper.stop();
},1000);
這將啟動您的回圈,您可以隨時停止它。但正如我所說,我不確定你想要實作什么
uj5u.com熱心網友回復:
如果我能理解,您正在這里尋找setInterval。您可以使用 intervalId 啟動和停止它。比使用 while 回圈和阻塞唯一的執行執行緒要好。
class Sniper {
constructor() {
this.Status = "Off";
this.intervalId = null;
}
start() {
this.Status = "On";
this.intervalId = setInterval(() => {
console.log(this.Status);
}, 1000);
}
stop() {
console.log("Turning off!");
this.Status = "Off";
clearInterval(this.intervalId);
}
}
const foo = new Sniper();
foo.start();
setTimeout(() => {
foo.stop();
}, 5000);
這將輸出:
On
On
On
On
Turning off!
希望這可以幫助..
快樂的編碼...
快樂學習...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457128.html
標籤:javascript 节点.js 班级
下一篇:回圈@with_kw結構
