Refreshing every XX seconds - actionscript-3

I am new to actionscript and flash, but i managed to make code that gets data from php file and refresh result every 30 seconds:
var timerRefreshRate:Number = 30000;
var fatherTime:Timer = new Timer(timerRefreshRate, 0);
fatherTime.addEventListener(TimerEvent.TIMER, testaa);
fatherTime.start();
function testaa(event:Event):void{
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,varsLoaded);
loader.load(new URLRequest("data.php"));
function varsLoaded (event:Event):void {
this.opaqueBackground = loader.data.color;
title.text=loader.data.title;
banner_text.text=loader.data.text;
}
}
But now i am facing 2 problems:
1.) User must wait 30 seconds for movie to load first time
2.) Setting background color does not work any more.
What am i doing wrong?

You can call your function once to load immediately without waiting 30 seconds. Just change the parameters of the function to default to a null event:
function testaa(event:Event = null):void{
//...
}
Now you can call the function like so:
//...
fatherTime.start();
testaa();
So you start the timer but immediately run the function once.
For your second problem, the issue is most likely that you are using a nested function, so this does not refer to your class but rather the testaa function. Nested functions are bad practice in general and you should avoid them if possible. Move the function and loader reference outside and it should work. Final result should be something like this:
var loader:URLLoader;
var timerRefreshRate:Number = 30000;
var fatherTime:Timer = new Timer(timerRefreshRate, 0);
fatherTime.addEventListener(TimerEvent.TIMER, testaa);
fatherTime.start();
testaa();
function testaa(event:Event = null):void{
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE,varsLoaded);
loader.load(new URLRequest("data.php"));
}
function varsLoaded (event:Event):void {
this.opaqueBackground = loader.data.color;
title.text=loader.data.title;
banner_text.text=loader.data.text;
}

Related

as3 return value on loader complete

I am trying to get my function to return a value from a php script once it has loaded. I am having issues with the 'return' aspect. Trying to the the value of 'TheLink" from a function with a 'return' in it. It's usually null. What am I doing wrong here?
var theLink = loadAudio();
public function loadAudio():String
{
var req:URLRequest = new URLRequest("myScript.php");
var loader:URLLoader = new URLLoader(req);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, Finished);
function Finished(e:Event)
{
var theValue = JSON.parse(e.target.data.audioLink);
return theValue;
}
}
A lot of things are wrong in your code but more important is that you cannot escape the asynchronous nature of AS3.
First thing first, even if AS3 wasn't asynchronous your code would still not work. The "loadAudio" never returns anything so theLink can never get any data. The 'Finished' method is the one return something but there's no variable to catch that data either.
Now the real stuff, AS3 is asynchronous that means that things will happen at a later time and this is why you need to pass an event listener in order to 'catch' when things happen. In your case the Event.COMPLETE will trigger at a later time (asynchronous) so there's no way for a variable to catch the result before the result is actually available so:
var theLink:Object = loadAudio();//this is not possible
The correct way is:
private var loader:URLLoader;//avoid GC
private var theLink:Object;//this will store result when available
//I assume you are using a class
public function MyClass()
{
loadAudio();//let's start loading stuff
}
private function loadAudio():void
{
var req:URLRequest = new URLRequest("myScript.php");
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, handleLoaded);
loader.load(req);
}
private function handleLoaded(e:Event):void
{
theLink = JSON.parse(e.target.data.audioLink);
//done loading so store results.
}

AS3 running an event for a set duration after button (or anything) event

For the purposes of the question, Imagine I have an object onstage. When I click on another button, I want the colour to change for 1 second, then revert back again when finished.
Here's what my demo code looks like:
Button.addEventListener(MouseEvent.CLICK, Colour_Change);
function Colour_Change(evt: MouseEvent): void {
var my_color: ColorTransform = new ColorTransform();
my_color.color = 0xFF0000;
Coloured_Object.transform.colorTransform = my_color;
}
What I am wanting is some sort of timer function to be incorporated in the above function. I haven't got any idea how to do it, hence why there's no implementation.
You should use the flash.utils.Timer class.Adobe ActionScript 3.0 Reference for the Timer class
The following should be enough to get you headed in the right direction:
import flash.utils.Timer;
var myTimer:Timer = new Timer(1000, 1); // 1 second
var running:Boolean = false;
Button.addEventListener(MouseEvent.CLICK, Colour_Change);
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
function Colour_Change(evt: MouseEvent): void {
var my_color: ColorTransform = new ColorTransform();
my_color.color = 0xFF0000;
Coloured_Object.transform.colorTransform = my_color;
if(!running) {
myTimer.start();
running = true;
}
}
function runOnce(event:TimerEvent):void {
// code to revert the button's color back goes here
myTimer.reset();
running = false;
}
Let me know if you need more help or if this example has errors via this answer's comments section.
To further explain the Timer class as used above:
when creating a new timer
myTimer=new Timer(1000,1)
the first number in the brackets is the number of milliseconds you want the timer to run for (e.g. 1000 = 1 second)
The second number is how many times you want the timer to repeat (or 0 for infinite repetition).
Every time the timer reaches the time you entered (1000), this is will trigger any event listeners for the event Timer_Event.TIMER, so for example if u wanted to make it change color on and off, you could have multiple repetitions on the timer and change the function.
Other useful things timers can do:
You can add an event listener for
Timer_Event.TIMER_COMPLETE
(goes off when all repetitions are complete)
myTimer.currentCount
will return the number of repetitions the timer has done so far.
To do that you can use, as other answers said, a Timer object or the setTimeout() function, like this :
// the current color of our target object
var default_color:ColorTransform;
// the delay in milliseconds
var delay:int = 1000;
btn.addEventListener(MouseEvent.CLICK, Colour_Change);
function Colour_Change(evt: MouseEvent): void {
// save the current color of our target object
default_color = target.transform.colorTransform;
var new_color:ColorTransform = new ColorTransform();
new_color.color = 0xFF0000;
target.transform.colorTransform = new_color;
var timer:Timer = new Timer(delay, 1);
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void {
// after the delay, we use the default color of our target
target.transform.colorTransform = default_color;
})
timer.start();
// using setTimeout(), you have to disable this if using the Timer
var timeout:int = setTimeout(
function(){
clearTimeout(timeout);
// after the delay, we use the default color of our target
target.transform.colorTransform = default_color;
},
delay
);
}
Hope that can help.

Running-order of nested function-calls delayed/altered due to URLloader in AS3?

First of all: English is not my first language. ;-)
I am compiling the following code:
var sqldata:String;
function sql(saveorload,sqlstring) {
var sqlloader = new URLLoader();
var sqlrequest = new URLRequest("http://***/sql.php");
sqlrequest.method = URLRequestMethod.POST;
sqlloader.addEventListener(Event.COMPLETE, sqldonetrace);
var variables:URLVariables = new URLVariables();
variables.sqlm = saveorload;
variables.sqlq = sqlstring;
sqlrequest.data = variables;
sqlloader.load(sqlrequest);
}
function sqldonetrace(e:Event) {
sqldata = e.target.data;
}
sql("1","SELECT * FROM songs WHERE `flag2` LIKE '0'");
trace (sqldata);
So, here comes the problem:
"sqldata" is traced as "null". AS3 seems to run "sql", then "trace" and then "sqldone", but i would need sql -> sqldone -> trace...
I can't put the trace-command in the sqldone-function because it is stored as *.as and loaded at different points in my .swf and not always followed by only a trace-command.
Any Ideas/hints/flaws in script?
Actionscript is, by design, an event driven language. It also guarantees that the code executes in a single thread i.e. if a function call starts, no other(new call) actionscript code would execute until the first call finishes.
That being said, what you should have is to pass a complete handler to sql(...).
function sql(saveorload:String, sqlstring:String, completeHandler:Function):void
{
var sqlloader = new URLLoader();
var sqlrequest = new URLRequest("http://***/sql.php");
sqlrequest.method = URLRequestMethod.POST;
sqlloader.addEventListener(Event.COMPLETE, completeHandler);//tell urlloader to use the complete handler passed in parameters
var variables:URLVariables = new URLVariables();
variables.sqlm = saveorload;
variables.sqlq = sqlstring;
sqlrequest.data = variables;
sqlloader.load(sqlrequest);
}
And then use it from some other place like:
sql("1","SELECT * FROM songs WHERE `flag2` LIKE '0'", sqldonetrace);
function sqldonetrace(e:Event)
{
var sqldata:String = e.target.data;
trace (sqldata);
}
Also, I think you should check for error events from urlloader. Pass another parameter to sql as errorHandler

NotificationType.CRITICAL needs only to only fire when file loaded is a new file

I have an Adobe Air desktop message board App built in Flash cs5, it loads an external ".txt" file in a dynamic text field and checks for a new file every 2 minutes. I need it to notify user with (NotificationType.CRITICAL) only if the file is new not just everytime it loads it. is it possible?
all the code in the app:
NativeApplication.nativeApplication.startAtLogin=true
stage.nativeWindow.alwaysInFront=true;
//external text file load and recheck every 2 minutes
var myInterval:uint = setInterval (loadUrl, 120000);
var loader:URLLoader = new URLLoader(new URLRequest("https://my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event):void {
var loadedText:URLLoader = URLLoader(event.target);
if(myText_txt.htmlText!=loadedText.data){
myText_txt.htmlText = loadedText.data;
stage.nativeWindow.notifyUser(NotificationType.CRITICAL)
}else {
//do nothing
}
}
function loadUrl():void {
loader = new URLLoader(new URLRequest("https:///my_text_file.txt"));
loader.addEventListener(Event.COMPLETE, completeHandler);
}
// button control
Minimize_BTN.addEventListener(MouseEvent.CLICK, minimize);
function minimize(e:MouseEvent){
stage.nativeWindow.minimize();
}
drag_BTN.addEventListener(MouseEvent.MOUSE_DOWN, drag);
function drag(e:MouseEvent){
stage.nativeWindow.startMove();
}
stop(); //Stop on the frame you want
Your code might not work if the myText_txt field is modifying the loaded text (e.g., if myText_txt's condenseWhite property is set to true). A more accurate way to determine if the text has changed would be to store it in a String variable named, for example, oldText and then comparing oldText with the newly loaded text.
Here's part of your code re-written to include the oldText variable. This code is also more efficient because it instantiates some variables only once and it avoids duplicating some code:
import flash.net.URLRequest;
function completeHandler(event:Event):void
{
var newText:String = loader.data;
if(newText != oldText)
{
myText_txt.htmlText = newText;
stage.nativeWindow.notifyUser(NotificationType.CRITICAL);
oldText = newText;
}
}
function loadUrl():void
{
loader.load(req);
}
// Initialize your variables and event handlers only one time
var req:URLRequest = new URLRequest("https:///my_text_file.txt");
// Set cacheResponse to false to prevent a successful response
// from being cached.
req.cacheResponse = false;
// And don't bother checking the cache, either.
// Not necessary, but the request will execute a little faster.
req.useCache = false;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
// Use oldText inside completeHandler() to determine
// whether the file's text has changed
var oldText:String = "";
var myInterval:uint = setInterval(loadUrl, 120000);
// Start loading the text right away
loadUrl();
Why don't you use FileReference object to find out about some properties like modificationDate and based on this verify if file is different you can also test it's size.

Force to refresh movie clip?

I have a really simple code piece like that;
loadingMc.visible = true;
trace("ok");
// send photo to server
loadingMc.visible = false;
Sending photo takes 3-5 seconds but movie clip becomes visible only for last second of process. I can see "ok" message in output at start of the process. So i assume problem is not redrawing movie clip. Is there any option to force redraw before process starts?
UPDATE:
Sending to server part;
upload.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
loadingText.visible = true;
trace("ok");
var bmd:BitmapData = new BitmapData(1024,768,true,0);
bmd.draw(imageArea);
savePicToServer(bmd);
});
function savePicToServer(bmd:BitmapData):void
{
var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(bmd);
var loader:URLLoader = new URLLoader();
configureListeners(loader);
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var request:URLRequest = new URLRequest("http://localhost/test/upload.php?key=prvkey");
request.requestHeaders.push(header);
request.method = URLRequestMethod.POST;
request.data = jpgStream;
loader.load(request);
}
In the COMPLETE event;
loadingText.visible = false;
EDIT
Just from reading your code, I don't see why this should not be working - but FP does strange things sometimes.
In similar cases, I used setTimeout() to force the player to delay the subsequent actions and allow the screen to refresh:
upload.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
loadingText.visible = true;
trace("ok");
setTimeout( doSave, 10 );
});
private function doSave() : void {
var bmd:BitmapData = new BitmapData(1024,768,true,0);
bmd.draw(imageArea);
savePicToServer(bmd);
}
If this still doesn't work, perhaps a longer timeout will do the trick - but 10ms usually should be enough to refresh the screen.
EDIT
Another way would be to add and remove an ENTER_FRAME listener to make sure the frame really was refreshed:
upload.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void{
loadingText.visible = true;
trace("ok");
addEventListener( Event.ENTER_FRAME, onNextFrame );
});
private function onNextFrame( ev:Event ) : void {
removeEventListener( Event.ENTER_FRAME, onNextFrame );
doSave();
}
private function doSave() : void {
var bmd:BitmapData = new BitmapData(1024,768,true,0);
bmd.draw(imageArea);
savePicToServer(bmd);
}