0

I am trying to have it so that after a certain amount of time a boolean that starts as false goes to true the code I have so far is here and I don't know how to set up a timer, could I get some help?

var alert1 == false;

if (alert1) {
alert ("Hello!");
} else {
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67

3 Answers3

1

Using setTimeout() method, where you can provide the time in milliseconds after that your code will be executed.

let alert = false;

console.log("Begin..... ", alert);
setTimeout(() => {
  alert = true;
  console.log("after 2 secs: ", alert);
}, 2000);

Check here for more detail.

Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
1

Use setTimeout to add a delay for executing code.

setTimeout(function () {
    alert1 = true;
}, YOUR_DELAY_TIME_IN_MILLISECONDS); // Replace with how much time you want to wait

Your code will not work because you check it if alert1 is true at the beginning of the script running, but a few moments later alert1 will change to true. You do not check if alert1 is true after you actually change it to true. If you want it to alert something in a few seconds, you do not need a boolean.

setTimeout(function () {
    alert("Hello!")
}, 2000); // Replace with how much time you want to wait in milliseconds (this is 2000 milliseconds, which is 2 seconds)
bub
  • 330
  • 2
  • 9
1

You use setTimeout

var alert1 = false;
// check alert1 value every second
setInterval(()=>{console.log(alert1)}, 1000);
// change it after 5s
setTimeout(() => {alert1 = true;}, 5000);
Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72