Timer delay in flash - actionscript-3

// AS3
var myTimer:Timer = new Timer(1000); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runMany);
myTimer.start();
function runMany(event:TimerEvent):void {
trace("runMany() called # " + getTimer() + " ms");
}
Expected output:
runMany() called # 1000 ms
Generated Output:
runMany() called # 12823 ms
runMany() called # 25603 ms
runMany() called # 38404 ms
Is this due to some short of software problem? I copied this easy code from Adobe Site but it's not working.

same code is working in flash CS6 actionscript 3.0 (gave unexpected O/P in CS4) so i think the problem might be of software. It said will installation that some features could not be installed properly and i ignored it....... Anyway Thanku all.

Related

SharedObject appears to be caching

I have a slightly unusual situation with SharedObject:
The situation: where we have a SWF (browser) based application running on a single local machine. The SWF accesses local content and is reloaded every XX number of seconds/minutes/hours.
The state of application has to be stored within a single SharedObject (this is using the '/' parameter to force it to global) in a JSON style.
The SWF loads the SO before it makes any state updates and correctly calls flush() immediately after to save state.
The Problem: Everything runs fine BUT occasionally there is a situation where by 2 instances of the same SWF are existing at the same in different instances and both are accessing the same SharedObject.
The 2nd has to take control of the SO from the 1st, by each SWF instance setting it's instance state to an incremented number (SWF Idx) stored in the SO.
Both are loading the file before any update is made, version number checked, and will disable themselves if the saved SWF Idx is above it's own. Unfortunately the 1st SWF instance somehow isn't loading the latest version of the SharedObject because it traces out the original number (e.g. 22) instead of the now updated one (e.g. 23). While the 2nd SWF is tracing out 23 and the SO contains 23.
Is there any way that the browser could possibly be caching the SO?
Testing
I'm currently testing the situation by running one browser instance locally then launching a 2nd. Making copies of the SO before and after each state.
I've also run the 1st and 2nd via IntelliJ and can see that SharedObject.getLocal is being called and checked each time.
I've included the basics of the code I'm using below where:
__so = is the public SharedObject variable
_thisSWFIdx = is the private variable inside AS3 storing the current instances SWF Index
__so.data.activeSWFIdx = the latest SWF Index
The SO 'get' I'm using is:
SharedObject.getLocal(_SO_ID, "/");
The check i'm doing is:
if (_thisSWFIdx < __so.data.activeSWFIdx) {
__amActiveSWF = false;
}
The saving of the variable to SO:
__so.data.activeSWFIdx = _thisSWFIdx;
flush();
Additonal info:
This is running on both mac & windows
FlashPlayer 10.3
Pure AS3
compiled in IntelliJ
same issue in FF, Chrome and IE
primary machine Macbook
I can't find anything within the documentation or existing threads so any help will be much appreciated.
After a little test, I remarked the behavior that you've mentioned : after updating the SharedObject by a second SWF, the first one can't get the new value only after a reload.
To avoid that, I think, as a workaround, you can use a second SWF which will just work on the SharedObject by reading / writing data.
For that, take this example :
so.swf : the SWF which will read and write data.
var shared_object_name:String = 'so';
var shared_object:SharedObject = SharedObject.getLocal(shared_object_name, '/');
// get the id
function get_id(): int {
return shared_object.data.id ? shared_object.data.id : -1;
}
// set the id
function set_id(new_id:int): void {
shared_object.data.id = new_id;
shared_object.flush();
}
app.swf : your global app which will use the "so.swf" to do SharedObject's operations :
var init:Boolean = true;
var swf_id:int = 1;
var swf_disabled:Boolean = false;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_SWFLoad);
loader.load(new URLRequest('so.swf'));
function on_SWFLoad(e:Event): void
{
var loaded_swf:MovieClip = MovieClip(loader.content);
var current_id:int = loaded_swf.get_id();
// if it's initial run
if(init){
init = false;
if(current_id > 0){
swf_id = current_id + 1;
}
loaded_swf.set_id(swf_id);
} else { // we are verifying if there is a new active SWF
if (swf_id <= current_id) {
swf_disabled = true;
}
}
}
function stage_onPress(e:MouseEvent){
// if this SWF is disabled, stop getting the "id"
if(swf_disabled){
stage.removeEventListener(MouseEvent.CLICK, stage_onPress);
return;
}
// otherwise, get the "id" to verify if there is another active SWF
loader.load(new URLRequest('so.swf'));
}
stage.addEventListener(MouseEvent.CLICK, stage_onPress);
I used MouseEvent.CLICK only for testing purposes, of course you have to use a Timer or something else to verify every n seconds (for example) that you have another active SWF to disable the current one...
Hope that can help.

PurePDF ImageElement throwing errors

Hey so I am trying to create an air app that generates a PDF for the user to save but am running into issues with PurePDF. Whenever I run the ImageElement.getInstance() method I am returned a runtime error:
Error: Error #2030: End of file was encountered. at flash.utils::ByteArray/readUnsignedByte()
I am still just in the testing stage and am not evening doing anything crazy. This is what my code looks like:
var bd:BitmapData = new BitmapData( 1024,768 );
bd.draw(pdfClip); //A simple movieclip on the stage containing an image
var bytes:ByteArray = bd.getPixels(new Rectangle(1024,768));
var image:ImageElement = ImageElement.getInstance( bytes );
I would be grateful if anyone that has used purePDF can offer any advice, the documentation is extremely limiting.
You should use the "getBitmapDataInstance" instead, because the "getInstance" method is expecting a png encoded bytearray.
ImageElement.getBitmapDataInstance( bitmap );
see also this example:
https://code.google.com/p/purepdf/source/browse/examples/src/ImageBitmapData.as

Action Script 3 Error after upgrade to Flash CS6

I recently upgraded to Flash CS6 from CS4. I didn't receive any errors with this script until CS6 but now I'm receiving the following error:
Symbol 'wholePlayer,Layer,'Layer9'Frame 3 Line 12 - 1152 A conflict exists with inherited definition flash.display:movieclip.isPlaying in namespace public.
Here's my script:
import flash.net.URLRequest;
stop();
// Create the sound object
var snd:Sound = new Sound();
// Assign a var name for the sound channel
var channel:SoundChannel;
// Initialize the pause position
var pausePosition:int = 0;
// Boolean value for button functions, to switch in the conditionals
var isPlaying:Boolean = false; ******HERE'S THE LINE REFERENCED IN THE ERROR*******
// Set the play buffer to 5 seconds, you can adjust this
var context:SoundLoaderContext = new SoundLoaderContext(5000,true);
// Load the requested URL sound into the snd var, along with context
snd.load(req, context);
// Create the play channel using snd
channel = snd.play();// Start playing
// --- Stop sound from autoplaying --- \\
if(firstTime == true)
{
stopSound(null);
}
It's script for an .MP3 player. I've indicated the line that's mentioned in the error above. Any help would be greatly appreciated. Thanks.
Solan
Version 11 of the Flash Player added a MovieClip property named isPlaying. Renaming your variable will solve the problem.

ActionScript 3.0 Error #1010 - preloader function

I am a Flash and ActionScript newbie. I am trying to follow a video tutorial to make a preloader and I'm having a problem that the video didn't seem to address. I believe I have entered in all of the code correctly from the video. This is it:
stop();
addEventListener(Event.ENTER_FRAME, loaderF);
function loaderF(e:Event):void{
var toLoad:Number = loaderInfo.bytesTotal;
var loaded:Number = loaderInfo.bytesLoaded;
var total:Number = loaded/toLoad;
if( loaded == toLoad ){
removeEventListener(Event.ENTER_FRAME, loaderF);
gotoAndStop(2);
} else {
preloader_mc.preloaderFill_mc.scaleX = total;
preloader_mc.percent_txt.text = Math.floor( total * 100 ) + "%";
preloader_mc.ofBytes_txt.text = loaded + "bytes";
preloader_mc.totalBytes_txt.text = toLoad + "bytes";
}
}
What I typed in doesn't generate a compiler error, but the output tells me:
TypeError: Error #1010: A term is undefined and has no properties.
at preloader_fla::MainTimeline/loaderF()
And since I really don't have any experience outside of what I'm learning from this tutorial series, I don't know what to do to fix this.
I don't use Flash CS5, but you should be able to get the line # for where the error is occurring, I believe, by executing the SWF by pressing CTRL+SHIFT+ENTER.
Once you get the line number, you should see that something on that line is null or not defined. The error says it occurs in the function loaderF(), and looking at that code the only place such an error could occur is in the else block:
} else {
preloader_mc.preloaderFill_mc.scaleX = total;
preloader_mc.percent_txt.text = Math.floor( total * 100 ) + "%";
preloader_mc.ofBytes_txt.text = loaded + "bytes";
preloader_mc.totalBytes_txt.text = toLoad + "bytes";
}
In the above code block, one of these things is not defined:
preloader_mc.preloaderFill_mc,
preloader_mc.percent_txt,
preloader_mc.ofBytes_txt,
preloader_mc.totalBytes_txt
Maybe your preloader movie clip is missing one of these objects...
First, you'll want to turn on debugging found under (File > Publish Settings > Flash (.swf) > Permit Debugging). This will provide line numbers and allow additional debugging to help track down errors.
Secondly, in the code sample you've provided, you haven't declared a loader, so when you call on loaderInfo, it makes sense that flash complains about "a term is undefined". Although, technically, the loaderInfo object is a child of the event object. Thus, loaderInfo.bytesTotal would become e.loaderInfo.bytesTotal, assuming you added the event listener to the loader object; currently yours is added to the timeline.
Bookmark Adobe's Actionscript 3.0 Reference. Use it. As you begin your journey in Flash, this will be your indispensable handbook to speaking AS3. Specifically, you'll want to refer to the Loader class.
Here's what you're likely missing in your code:
var myLoader:Loader = new Loader();
myLoader.load(new URLRequest("path/to/my/file"));
Your function loaderF is being called during every frame update to the screen (likely every .034 seconds). You'd probably be happier with ProgressEvent.PROGRESS instead of Event.ENTER_FRAME. If so, you'll also want to catch the complete event, and that'd look like this:
myLoader.addEventListener(Event.COMPLETE, loadComplete);
myLoader.addEventListener(ProgressEvent.PROGRESS, loadProgress);
function loadComplete(e:Event):void {
// Stuff to do when the file finishes loading.
}
function loadProgress(e:Event):void {
var current:int = e.bytesLoaded;
var total:int = e.bytesTotal;
var percent:Number = current/total;
// Update the readout of your loading progress.
}
Hopefully that points you in the right direction. :)

Adobe Air, packaged install fails with my trace routine... how come?

I cobbled together some code from here and there for a trace I like... it generates an error to get a stack trace and picks out the traced routine name, I like that detail in the trace log.
Problem: it fails in an installed AIR file. I wonder why? I don't expect it to do anything as is... just, I'd prefer it not cause the program to fail!
tx
artie
enter code here
static public function XTRACE( ... traceArgs ):void {
try {
throw new Error(); // make a stack
} catch (e:Error) {
var stack:String = e.getStackTrace();
var frames:Array = stack.split("\n");
var myFrame:String = String(frames[2]);
myFrame = myFrame.replace("\t", "");
// "at " can be followed by some part of the package
// you don't want to see. E.g., if your code is all in
// com.foo.bar, you can put "at com.foo.bar." so as not
// to crowd the display
myFrame = myFrame.substr("at ".length);
myFrame = myFrame.substring(0, myFrame.indexOf("["));
var now:Date = new Date();
trace(new Date().toLocaleTimeString() + ":" + myFrame + ": " + traceArgs.join(" "));
}
}
In what way is your app failing?
1) Trace routines are for debugging, so your trace won't do anything in an installed app.
2) I'm not sure when you call this routine, but it seems weird that you have a routine that only throws an error. I think in this code the 'catch' is only going to get entered if there's an error throwing the error. Normally you would try to perform some useful action, and catch errors when something goes wrong.
Within the trace function your attempting to invoke the Date().toLocaleTimeString() statically before it becomes instantiated by the new keyword. Try the following instead:
trace((new Date()).toLocaleTimeString() + ":" + myFrame + ": " + traceArgs.join(" "));
thanks for your input Fergal. The XTRACE function works fine running with the debug player, and fails only when running with the release player. So I assume the code line I use must associate values in the right order... I settled on using a function I didn't know about before:
enter code here
static public function XTRACE( ... traceArgs ):void {
if ( Capabilities.isDebugger ) {
With that, XTRACE does nothing unless it is executing in a debug environment. So it works around the issue. I'll still use your brackets though, I like to make order of association obvious too ;-)
I realize you've probably grown old and forgot what flash is since you asked this question. But, you're getting an NPE because e.getStackTrace() returns null in the release player.
A couple other things:
You don't need to throw the error to get a stack trace; new Error().getStackTrace() works fine.
Since this is debug code, and the calling code probably isn't expecting errors, you should wrap the whole thing in a try catch.
The compiler won't resolve 'at '.length, so it will be called every time at runtime. Unless you're really paranoid, you can just hard code it to 3.
Both the substrs can be combined into 1
The now variable isn't used.