- Home /
Better way to delay a function for a few seconds? Javascript
It is more of an "inconvenience" than a problem.
I often find myself creating a bunch of booleans in order to stop something from happening more than ones.
Exsample
private var ReadyToFire : boolean = true;
function Update() {
if(pulltrigger && ReadyToFire) { ReadyToFire = false; fire(); resetReadyToFire(); } }
function resetReadyToFire(){ yield WaitForSeconds(2); ReadyToFire = true; }
Every time I do this, I feel like there has to be a simpler way to achieve what I am after. I always end up with a ton of functions and boolean variables just because I need to delay something.
Answer by Eric5h5 · Sep 23, 2010 at 11:36 PM
Don't use Update...it runs every frame, so to make stuff not happen every frame, you need a bunch of hacks, as you discovered. Just stick to coroutines instead.
function Start () {
while (true) {
while (!pullTrigger) yield;
Fire();
yield WaitForSeconds(2.0);
}
}
I will have to get a little bit more familiar with while statements. I am working on my 3rd iPhone game but I have been hacking my way thru every peace of code. I am a 3D Artist lol. I use "If" statements for everything.
if I use this while statment in the Start function, it will continue to be called all game even tho it is only called ones? I guess because it is a loop. Sounds good, I will look up how to use while statements, I think I saw a youtube video on it ones. Thanx for the tip, I am sure ones I get it down it can save me a lot of trouble.
I just put it to the test, It works great. New weapon in my fight for creating games. Thank you.
@Anxo: A while loop continues to loop as long as the condition is true, and by just using "true", that means it will always loop, forever. (Since "true" is always true....) Although you can use "break" to stop it.