Frage

In my flex mobile application, I have a loop running for over 100 iterations. In each iteration I'm updating some properties of specific Label(s). Since the loop is time consuming, I need to update the screen and display intermediate results at each iteration. How can I break the loop and refresh the display list?

function theFunction():void{
 for var i:int = 0; i < n; i++{
  doBusyStuff();
  label_1.text = "iteration"+" i";
 }
}
War es hilfreich?

Lösung

In that situation, I prefer to use flash.utils.setTimeout()

import flash.utils.setTimeout;

function theFunction(limit:int, current:int = 0):void 
{
    if (current >= limit)
        return;

    doBusyStuff();
    label_1.text = "iteration "+ current.toString();

    setTimeout(theFunction, 0, limit, current+1);
}

However, both setTimeout() and callLater() depend on the tick or the frame rate, meaning that they won't do as fast as they can. So if you also want it to run faster, you should have it run a few loops per each call.

Andere Tipps

Another solution, similar to Chaniks' answer, uses DateTime to check how long the loop has been running on each iteration. Once it detects that it's been running for too long, it ends the loop and picks up again on the next Frame.

var i:int;
function callingFunction():void {
  i = 0;
  stage.addEventListener(Event.ENTER_FRAME, theFunction);
}

function theFunction(e:Event):void {
  var time:DateTime = new DateTime();
  var allowableTime:int = 30;  //Allow 30ms per frame
  while ((new DateTime().time - time.time < allowableTime) && i < n) {
    doBusyStuff();
    i++;
  }
  if (i >= n) {
    stage.removeEventListener(Event.ENTER_FRAME, theFunction);
  }
  label_1.text = "iteration"+" i";
}

There are several methods to force redraw of components:

invalidateDisplayList();
invalidateProperties();
invalidateSize();

Just use whatever you need for your components inside a function and call it after your script using callLater(yourRedrawFunction);

EDIT: For example, in your case:

function theFunction():void{
 for var i:int = 0; i < n; i++{
  doBusyStuff();
  label_1.text = "iteration"+" i";
 }
 callLater(yourRedrawFunction);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top