CrownFord
CrownFord

Reputation: 719

Flash AS3, How to pause a loop for seconds

I have this AS3 script (it works fine), I just want to make the loop to pause for seconds each time then it can continue looping. Like if I like it to stop for Milliseconds.Thanks

var myText:String; 
var counter:int = 0; 

var format : TextFormat = new TextFormat();
format.size = 16;
format.font = "Verdana";
format.bold = true;
format.color = 0x000000; 

var textField : TextField = new TextField();
textField.width = 200;
textField.height = 50;
textField.selectable = false;
textField.wordWrap = true;
textField.defaultTextFormat = format;
textField.x = textField.y =0;
addChild(textField);
				
var textLoader:URLLoader = new URLLoader(new URLRequest("text.txt"));
textLoader.addEventListener(Event.COMPLETE, function(e:Event){initText(e.target.data);});

function initText(string:String):void{
	myText = string; 
	addEventListener(Event.ENTER_FRAME, writeText); 
}

function writeText(e:Event):void{
	if (counter <= myText.length){
   	     textField.text = myText.substr(0,counter); 
   	     counter++;
         /*What I can put here to make it pause for a while*/
	}
	else{
		removeEventListener(Event.ENTER_FRAME,writeText); 
	}
}

Upvotes: 1

Views: 395

Answers (1)

Organis
Organis

Reputation: 7316

Your code is fine, you need to tweak it a little bit.

function initText(string:String):void
{
    myText = string; 
    addEventListener(Event.ENTER_FRAME, writeText); 
}

// Variable to keep the next print time in milliseconds.
var nextPrint:int;

function writeText(e:Event):void
{
    // Function getTimer() returns time in milliseconds since app start.
    // Skip this frame if time is not right.
    if (getTimer() < nextPrint) return;

    // Variable nextPrint is initially 0 so the first char will print immediately.

    if (counter <= myText.length)
    {
        textField.text = myText.substr(0, counter); 
        counter++;

        /*What I can put here to make it pause for a while*/
        // Print next character in ~100 ms.
        nextPrint = getTimer() + 100;
    }
    else
    {
        removeEventListener(Event.ENTER_FRAME, writeText); 
    }
}

Upvotes: 2

Related Questions