How to delay a while loop?

Would this code delay the time between every time the loop gets fired?

  while (coin.x > objYEnemy.x) {

    var delay:Timer = new Timer(100, 1);
    delay.addEventListener(TimerEvent.TIMER, runOnce);
    delay.start();
    function runOnce(event:TimerEvent):void {
            coin.x -= 1;
    delay.stop();
    }
}

Answers


Not really. Your loop will keep running over and over (for at least 100ms while your timer waits to fire), creating a new timer every time and creating a memory leak because your timers will never get disposed of on account of their event listener. Since your runOnce is an anonymous function, it will also get run a whole lot of times for every timer that gets created.

Without the knowing exactly what you're trying to accomplish, it would seem what you'll want to do is have the timer tick handler be the loop function.

var checkTimer:Timer = new Timer(100);
checkTimer.addEventListener(TimerEvent.TIMER, doCheck);
checkTimer.start();

function doCheck(e:Event):void {
    if(coin.x > objYEnemy.x){
        coin.x -= 1;
        //If you want this to only happen once, then add the following line:
        checkTimer.stop();       
    }
}

Need Your Help

Where is a good place to put common business logic that should run on every view?

c# asp.net asp.net-mvc

I have a project in which I need to check for and add a cookie, regardless of which view the user is currently on. I can place the code inside of the _Layout partial view within a code block, but I...