What I’m trying to do is to wait until the correct key is pressed for it to continue
The code i’ve done so far is this:
class exampleClass {
async waitForKeyPress() {
return new Promise((resolve) => {
const listener = (e) => {
document.body.removeEventListener("keydown", listener);
if(e.key == "z") {resolve(); alert("e");}
else {
this.waitForKeyPress();
}
}
document.body.addEventListener("keydown", listener);
});
}
async doStuff() {
await this.waitForKeyPress();
console.log("correct key pressed");
//do stuff
}
}
let exampleObject = new exampleClass();
exampleObject.doStuff();
This doesn’t work for me since if I press a different key then it doesn’t detect that the z key is pressed for some reason
The part that is confusing for me is is that if you do
async function waitForKeyPress() {
return new Promise((resolve) => {
const listener = (e) => {
document.body.removeEventListener("keydown", listener);
if(e.key == "z") resolve();
else {
this.waitForKeyPress();
}
}
document.body.addEventListener("keydown", listener);
});
}
async function doStuff() {
await this.waitForKeyPress();
console.log("correct key pressed");
//do stuff
}
doStuff();
it works, the only difference is that it’s not in a class. However, I would like it to be in a class
>Solution :
Remove listener only when z is pressed instead of removing it prematurely.
class exampleClass {
async waitForKeyPress() {
return new Promise((resolve) => {
const listener = (e) => {
if(e.key === "z") {
window.removeEventListener("keydown", listener);
resolve();
}
}
window.addEventListener("keydown", listener);
});
}
async doStuff() {
await this.waitForKeyPress();
console.log("correct key pressed");
//do stuff
}
}
let exampleObject = new exampleClass();
exampleObject.doStuff();
Without promise,
class exampleClass {
constructor() {
// the reason for this line is because "this"
// inside doStuff will be window instead of
// the class itself.
this.doStuff = this.doStuff.bind(this)
window.addEventListener("keydown", this.doStuff);
}
doStuff(e) {
if(e.key !== 'z') return
window.removeEventListener("keydown", this.doStuff)
console.log("correct key pressed");
//do stuff
}
}
let exampleObject = new exampleClass();