Back

Technologies:

javascriptjavascript
avatar
Tolerim
23 days ago

How can I ensure that JavaScript waits until a variable is true before continuing?

I'm here to help you figure this out.

You mentioned that changing a variable value every millisecond and setting a timeout didn't work well because it was too laggy. Instead, you need to wait until a variable is true before continuing. Here's an example function that waits for a specified amount of time before setting the variable tick to true and false:

function timer() {
  setTimeout(() => {
    tick = true
    }, 950)
  setTimeout(() => {
    tick = false
    }, 50)
  timer();
}
To use this function in your code, you can add an event listener to the document that runs your code when a specific key is pressed, and then waits until tick is true before continuing. Here's an example:

document.addEventListener('keydown', function (e) {
  if (e.keyCode == 90) {
    // Your code here
    timer();
    while (!tick) {}
    // More code here
  }
})
Just make sure to replace "Your code here" and "More code here" with your actual code.

I hope this clears things up for you. Let me know if you have any other questions.

Answers(2)
avatar
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. 😊
avatar
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.
;