How to make something happen after a certain amount of time

Im having trouble with a lot of my games. For a lot of my games i want something to happen after a couple seconds but i dont know how to do that

You could create a variable, and increment it, and check if the variable is at a certain value. Then “make something happen” like this:

// default script
this.timer = 0;
// update script
if (this.timer === project.framerate * 2) {
  // do something
} else {
  this.timer++
}

This code checks if the variable this.timer is equal to the project framerate, multiplied by 2, to wait 2 seconds to then “do something”.

1 Like

Like @awc95014 said in an other thread: don’t compare numbers absolutely to 0., This will fail randomly, especcialy if you do this agains a calculation. (ie: *2). This is because of JS. Instead, subtract the numbers from eachother, and check if the result is very small. Say, < 0.0001. This will not fail, as the (ronding) error in JS is very small. Thus, the code would be:

// update script
if ((this.timer - project.framerate * 2) < 0.001) {
    // do something
} else {
    this.timer++
}
2 Likes

You could also use a Date object if you want to use basically deltaTime, since it uses time instead of frames, which can be inconsistent.

For more info on Date objects, go here:

1 Like