x


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.

more ▼

asked Sep 23 '10 at 11:10 PM

Anxowtf gravatar image

Anxowtf
1.6k 22 27 38

(comments are locked)
10|3000 characters needed characters left

1 answer: sort oldest

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);
   }
}
more ▼

answered Sep 23 '10 at 11:36 PM

Eric5h5 gravatar image

Eric5h5
81.5k 42 133 529

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.

Sep 23 '10 at 11:47 PM Anxowtf

I just put it to the test, It works great. New weapon in my fight for creating games. Thank you.

Sep 23 '10 at 11:58 PM Anxowtf

@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.

Sep 24 '10 at 12:06 AM Eric5h5
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3570
x499
x249
x182

asked: Sep 23 '10 at 11:10 PM

Seen: 12897 times

Last Updated: Dec 30 '11 at 10:45 PM