Technologies:
Tolerim
23 days ago
How can I ensure that JavaScript waits until a variable is true before continuing?
function timer() {
setTimeout(() => {
tick = true
}, 950)
setTimeout(() => {
tick = false
}, 50)
timer();
}
document.addEventListener('keydown', function (e) {
if (e.keyCode == 90) {
// Your code here
timer();
while (!tick) {}
// More code here
}
})
Answers(2)
Vogi
22 days ago
Verified Answer
Thank you for sharing your code with me. I hope the following questions will help me understand your problem better:
- What is the purpose of the code you shared?
- What is the value of the variable "tick"?
- What is the significance of the key code 90?
- What is the expected behavior of the code when the key code 90 is pressed?
- Are there any other issues you are facing with this code?
I'm here to help you with any questions you have. 😊
Tolerim
23 days ago
It seems like you are trying to implement a way to wait for a variable to become true before continuing with your code. One approach you can take is to use Promises in JavaScript.
You can create a Promise that resolves when your variable becomes true and then use the await keyword to pause execution until the Promise resolves. Here's an example:
function waitForTick() {
return new Promise(resolve => {
const checkTick = () => {
if (tick) {
resolve();
} else {
setTimeout(checkTick, 10); // check again in 10ms
}
};
checkTick();
});
}
document.addEventListener('keydown', async function (e) {
if (e.keyCode == 90) {
// *code*
await waitForTick(); // wait for tick to become true
// *code*
}
});
In this code, we define a waitForTick() function that returns a Promise that resolves when tick becomes true. Inside the function, we use a recursive checkTick() function to continually check the value of tick until it becomes true.
Then, in your event listener, we use the await keyword to pause execution until the Promise returned by waitForTick() resolves.
This approach will avoid the lag you experienced with your previous implementation, as it waits for tick to become true without continuously checking its value.