How to wait for 3 seconds in ActionScript 2 or 3? - actionscript

Is there any way to implement waiting for, say, 3 seconds in ActionScript, but to stay within same function? I have looked setInterval, setTimeOut and similar functions, but what I really need is this:
public function foo(param1, param2, param3) {
//do something here
//wait for 3 seconds
//3 seconds have passed, now do something more
}
In case you wonder why I need this - it is a legal requirement, and no, I can't change it.

Use the Timer to call a function after 3 seconds.
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, callback); // will call callback()
timer.start();
To do this properly, you should create the timer as an instance variable so you can remove the listener and the timer instance when the function is called, to avoid leaks.
class Test {
private var timer:Timer = new Timer(3000);
public function foo(param1:int, param2:int, param3:int):void {
// do something here
timer.addEventListener(TimerEvent.TIMER, fooPartTwo);
timer.start();
}
private function fooPartTwo(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, fooPartTwo);
timer = null;
// 3 seconds have passed, now do something more
}
}
You could also use another function inside your foo function and retain scope, so you don't need to pass variables around.
function foo(param1:int, param2:int, param3:int):void {
var x:int = 2; // you can use variables as you would normally
// do something here
var timer:Timer = new Timer(3000);
var afterWaiting:Function = function(event:TimerEvent):void {
timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
timer = null;
// 3 seconds have passed, now do something more
// the scope is retained and you can still refer to the variables you
// used earlier
x += 2;
}
timer.addEventListener(TimerEvent.TIMER, afterWaiting);
timer.start();
}

For AS3 use Radu's answer.
For AS2 use the setInterval function like so:
var timer = setInterval(function, 3000, param1, param2);
function (param1, param2) {
// your function here
clearInterval(timer);
}

You can also use delayedCall, from TweenMax. IMHO, it's the sharpest way to do that if you are familiar to TweenMax family.
TweenMax.delayedCall(1, myFunction, ["param1", 2]);
function myFunction(param1:String, param2:Number):void
{
trace("called myFunction and passed params: " + param1 + ", " + param2);
}
In your case, using a anonymous function:
public function foo(param1, param2, param3) {
//do something here
trace("I gonna wait 3 seconds");
TweenMax.delayedCall(3, function()
{
trace("3 seconds have passed");
});
}

why you are doing some confused ways instead of doing the right way?
there is a method named:"setTimeout()";
setTimeout(myFunction,3000);
myFunction is the function you want to call after the period.and 3000 is the period you want to wait(as miliseconds).
you don't need to set then clear interval, or make a timer with one repeat count or do sth else with more trouble☺.

There is no Sleep in ActionScript. But there are other ways to achieve the same thing without having all your code in a single function and wait within that function a specific amount of time.
You can easily have your code in two functions and call the 2nd one after a specific timeout you set in your 1st function.

THIS IS NOT WITHIN ONE FUNCTION - ANSWERS: "How to wait for X seconds in AS2 & 3"
...without using setInterval or clearInterval.
The answers posted above are much faster and easier to use. I posted this here, just in case...
Sometimes you may not be able to use set/clearInterval or other methods based on development restrictions. Here is a way to make a delay happen without using those methods.
AS2 - If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
I have an onEnterFrame countdown timer in here as well, (demos stopping/switching timers).
If you want the delay/glow to be longer - increase the glowGameTime number. Change the names to fit your own needs and/or apply the logic differently.
var startTime:Number = 0;
var currentTime:Number = 0;
var mainTime:Number = 5;//"game" time on enter frame
var glowStartTime:Number = 0;
var glowCurrentTime:Number = 0;
var glowGameTime:Number = 1.8;//"delayed" time on press
btnGlowTest._visible = false;
this.onEnterFrame = TimerFunction;
startTime = getTimer();
function TimerFunction()
{
currentTime = getTimer();
var timeLeft:Number = mainTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up...3 bucks off");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
function glowTimerFunction()
{
glowCurrentTime = getTimer();
var glowTimeLeft:Number = glowGameTime - ((glowCurrentTime - glowStartTime)/1000);
glowTimeLeft = Math.floor(glowTimeLeft);
//trace("glowTimeleft = " + glowTimeLeft);
if(glowTimeLeft <= 0)
{
trace("TIME DELAY COMPLETE!");
//...do stuff here
btnGlowTest._visible = false;//just for show
btnTest._visible = false;//just for show
StopTime();
}
}
btnTest.onPress = function()
{
trace("onPress");
btnGlowTest._visible = true;
StopTime();
GlowTime();
}
function GlowTime()
{
trace("GlowTime Function");
this.onEnterFrame = glowTimerFunction;
glowStartTime = getTimer();
}
function StopTime()
{
trace(">>--StopTime--<<");
delete this.onEnterFrame;
}
AS3 - Below is the code from above setup to run in AS3. There are different ways to accomplish similar results, yet based on the project scope, these are the methods that were used in order to get things functioning properly.
If you copy/paste the code below to your timeline, make sure to add two movie clips to the stage, btnTest and btnGlowTest (include like instance names). Make "btnGlowTest" larger, a different color, & behind "btnTest" (to simulate a glow and a button, respectively).
Compile and check the output panel for the trace statements to see how the code is working. Click on btnTest - btnGlowTest will then become visible throughout the duration of the delay, (just for visual representation).
If you want the delay/glow to be longer - increase the GlowTimer:Timer number, (currently set to 950). Change the names to fit your own needs and/or apply the logic differently.
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var startTime:Number = 0;
var currentTime:Number = 0;
var gameTime:Number = 4;//"game" time on enter frame
var GlowTimer:Timer = new Timer(950,0);//"delayed" time on press
btnGlowTest.visible = false;
GlowTimer.addEventListener(TimerEvent.TIMER, GlowTimeListener, false, 0, true);
btnTest.addEventListener(MouseEvent.MOUSE_DOWN, btnTestPressed, false, 0, true);
addEventListener(Event.ENTER_FRAME,TimerFunction, false, 0, true);
startTime = getTimer();
function TimerFunction(event:Event)
{
currentTime = getTimer();
var timeLeft:Number = gameTime - ((currentTime - startTime)/1000);
timeLeft = Math.floor(timeLeft);
trace("timeLeft = " + timeLeft);
if(timeLeft <= 0)
{
trace("time's up, 3 bucks off");
StopTime();
}
}
function GlowTimeListener (e:TimerEvent):void
{
trace("TIME DELAY COMPLETE!");
StopTime();
}
function btnTestPressed(e:MouseEvent)
{
trace("PRESSED");
removeEventListener(Event.ENTER_FRAME, TimerFunction);
btnGlowTest.visible = true;
GlowTimer.start();
}
function StopTime()
{
trace(">>--Stop Time--<<");
btnGlowTest.visible = false;//just for show
btnTest.visible = false;//just for show
GlowTimer.stop();
removeEventListener(TimerEvent.TIMER, GlowTimeListener);
removeEventListener(Event.ENTER_FRAME, TimerFunction);
}

Related

Prevent the creation of events with conflicting times with FullCalendar

I'm trying to disable dayclick from functioning when there is already an event at the time. Is this possible? I've seen functions that stop people dragging one event to a conflicting time, but nothing that acts before creation.
Thanks
I've sorted it with click events function
function checkOverlap(event) {
var start = new Date(event);
var end = new Date(event.end);
var overlap = $('#calendar').fullCalendar('clientEvents', function(ev) {
if( ev == event) {
return false;
}
var estart = new Date(ev.start);
var eend = new Date(ev.end);
return (Math.round(estart) == Math.round(start));
});
if (overlap.length){
return false;
} else {
return true;
}
}
This is mostly possible because my app only allows users to make appointments for 1 hour and always on the hour. If you have a more flexible model where you can have variable length and starting time of the appointments, you will have to fiddle with the following line:
return (Math.round(estart) == Math.round(start));

Task with infinite cycle

I'm new in C#, I've gone to it from Delphi. So may be I do something wrong. My app (windows service) make tasks to control on-off states and count "on" time. I've tried to use Task.Delay(x), but it seems I catch deadlocks...
Main idea make tasks with infinite cycle which performs every x ms. I don't know if I could use the Timer for executing part code in lambda method of task...?
int TagCnt = DataCtrl.TagList.Count;
stopExec = false;
if (TagCnt != 0)
{
tasks = new Task[TagCnt];
for (int i = 0; i <= TagCnt - 1; i++)
{
int TempID = i;
tasks[TempID] = Task.Run(async () => // make threads for parallel read-write tasks // async
{
Random rand = new Random();
TimeSpan delay = TimeSpan.FromMilliseconds(rand.Next(1000, 1500))
try
{
while (!stopExec)
{
cToken.ThrowIfCancellationRequested();
//do basic job here
await Task.Delay(delay, cToken);
}//while end
}
catch (...)
{
...
}
}, cToken);
}
A couple of things went wrong here:
The tasks you're creating are completed instantly, in your case Task.Factory.StartNew returns Task<Task> because of the async lambda. To make it work as expected, unwrap the inner task with Task.Unwrap. Also, remove TaskCreationOptions.LongRunning, you don't need it here:
tasks[TempID] = Task.Factory.StartNew(async () => { ...}).Unwrap();
Alternatively, use Task.Run, it unwraps automatically (more about this):
tasks[TempID] = Task.Run(async () => { ...});
Besides, there's no synchronization context installed on a Windows service thread by default. Thus, the code after await Task.Delay() will be executing on a new pool thread each time, you should be ready for this.
Task.Delay is a bit different from a periodic timer. It will delay the execution. Use Stopwatch to calculate how much to delay for:
// beginning of the loop
stopwatch.Reset();
stopwatch.Start();
// the loop body
// ...
// end of the loop
await Task.Delay(Math.Max(500-Stopwatch.ElapsedMilliseconds, 0));

In Actionscript, is there a way to create a copy or cached version of a Loader?

I'm loading an SWF animation and want to display it in multiple places concurrently, but the only way I could figure out how to do that is to load it every time I display it, as seen here:
private function playSounds():void {
for (var i:Number = 0; i < 14; i++)
{
for (var a:Number = 0; a < 16; a++)
{
if (boxes[i][a].x == linePos && boxes[i][a].selected == true && played[i][a] == false)
{
played[i][a] = true;
MovieClip();
var swf:URLRequest = new URLRequest("../assets/glow2.swf")
var glow:Loader = new Loader()
glow.load(swf)
glow.x = boxes[i][a].x - 25*0.7;
glow.y = boxes[i][a].y - 27*0.7;
glow.scaleX = 0.7;
glow.scaleY = 0.7;
this.addChild(glow);
glows.push(glow)
glowTime.push(0)
var sc:SoundChannel = new SoundChannel();
sc = (sounds[i] as Sound).play();
}
}
}
}
This is very very slow when it's being displayed more than, say, 5 times at once so I'm wondering if there's a way to only have to load it once and use it in multiple places.
You have the content property of the Loader.
Thus, load once, use the content many times.
edit: you may want to add a listener to know when the loading completes, before you use the loaded content:
addEventListener(Event.COMPLETE, completeHandler);
edit2:
var mc1:MovieClip = new MovieClip();
var mc2:MovieClip = new MovieClip();
var my_Loader:Loader = new Loader();
mc1.addChild(my_Loader);
mc2.addChild(my_Loader);
(haven't tried though).
One quick workaround is to create a second loader and pass the loaded bytes to that via the loadBytes() method:
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE,ready);
l.load(new URLRequest("../assets/glow2.swf"));
function ready(event:Event):void{
var mc:MovieClip = event.currentTarget.content as MovieClip;
var clone:Loader = new Loader();
clone.loadBytes(event.currentTarget.bytes);
addChild(mc);
addChild(clone);
clone.x = 100;
}
This will work in most cases. In some cases you should be able to get away with something as simple as:
var clone:MovieClip = MovieClip(new mc.constructor());
And there is also a 3rd option: 'blitting' your moviclip, which means you'll store one or more (depending how many MoveClip frames you need to cache) of BitmapData objects in memory which will draw() from the source MovieClip you want to draw (in multiple locations at the same time).
The loadBytes approach achieves what the question suggests: creates a copy of the Loader, so it re-uses the bytes loaded, but initializes new content, so uses memory for that.
If this is not what you need, caching the MovieClip using BitmapData is your best bet.

AS3 time that needs to pause

I'm working on a mobile game and need the game clock to pause when the game loses focus, for example when call comes in. I have everything working except that when the game gains focus again the time adjusts to as if it had been running the whole time. If someone is on a 3 minute call when they get back they should find the game time where it was.
Here is my code:
public function showTime(event:Event){
gameTime = getTimer()-gameStartTime;
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function clockTime(ms:int) {
var seconds:int = Math.floor(ms/1000);
var minutes:int = Math.floor(seconds/60);
seconds -= minutes*60;
var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
return timeString;
}
public function onActivate(event:Event):void {
addEventListener(Event.ENTER_FRAME, showTime);
}
public function onDeactivate(event:Event):void {
removeEventListener(Event.ENTER_FRAME, showTime);
}
I've been Googling this for two days and am stuck. Could someone please point me in the right direction? Some sample code would be a benefit too since I'm pretty new to AS3. Thanks!
Rich
You can check out this Stopwatch tutorial that I wrote a while back:
http://www.popamihai.com/2010/10/flex/using-the-timer-class-in-flex-to-display-a-simple-stopwatch/
It is written with Flex Builder 3 but you could easily copy/paste the code. Example with view source enabled is also included
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
backgroundColor="white" viewSourceURL="srcview/index.html" creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.events.TimerEvent;
private const TIMER_INTERVAL:int = 50;
private var timerAtStart:Number = 0;
private var timerAtPause:Number = 0;
private var t:Timer;
private var d:Date;
[Bindable] private var sec:int = 0;
[Bindable] private var min:int = 0;
[Bindable] private var mls:int = 0;
private function init():void {
t = new Timer(TIMER_INTERVAL);
t.addEventListener( TimerEvent.TIMER, updateTimer );
}
private function updateTimer( evt:TimerEvent ):void{
d = new Date( getTimer() - timerAtStart + timerAtPause);
min = d.minutes;
sec = d.seconds;
mls = d.milliseconds;
}
private function startPauseTimer( event:MouseEvent ):void{
if ( event.target.label == "start" ) {
event.target.label = "pause";
timerAtStart = getTimer();
t.start();
} else {
event.target.label = "start";
timerAtPause = min * 60000 + sec * 1000 + mls;
t.stop();
}
}
]]>
</mx:Script>
<mx:Label text="{min + ' : ' + sec + ' : ' + mls}" fontSize="16" fontWeight="bold"/>
<mx:HBox>
<mx:Button label="start" click="startPauseTimer( event )"/>
</mx:HBox>
</mx:Application>
You're calculating your time based on the current time - gameStartTime. You either need to take the delay into account (calculate the total time stopped by using getTimer() in the onActivate() and onDeactivate() functions, then add that difference to gameStartTime), or if you don't want to change gameStartTime, then you calcuate your time based on delta time. Something like:
private var m_prevTime:int = 0;
public function startGame():void
{
// set the prevTime only when you start the game, otherwise you'll
// take into account all the time for flash to get going, your init,
// opening screens etc
this.m_prevTime = getTimer();
}
public function showTime(event:Event)
{
// get the difference in time
var currTime:int = getTimer();
gameTime += currTime - this.m_prevTime // currTime - prevTime = delta time
this.m_prevTime = currTime; // hold the current time
// display it
timeDisplay.text = "Time: "+clockTime(gameTime);
}
public function onActivate(event:Event):void
{
// we're reactivating, so make sure prev time is updated
this.m_prevTime = getTimer();
addEventListener(Event.ENTER_FRAME, showTime);
}
You'll miss out on a frame's time when coming back from the update, but it's not noticable (or you can subtract a frame's time in the onActivate() function)
Instead of using getTimer(), you should create a timer object and add an event listener to "tick" to update the clock. You can even set it to tick once per second so you don't have to convert the MS.
public function onActivate(event:Event):void {
myTimer.start();
}
public function onDeactivate(event:Event):void {
myTimer.stop();
}
See the timer reference: http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/utils/Timer.html

Errors in Action Script 3 in streaming .mp3 player

I'm trying to build a streaming .mp3 player to run various sound files on my web site. To do that, I followed a tutorial that includes a code template at:
http://blog.0tutor.com/post.aspx?id=202&title=Mp3%20player%20with%20volume%20slider%20using%20Actionscript%203
However, whether I preserve the template's direction to the author's own sound file or insert my own direction to my online sound file, I keep on running into glitches in the ActionScript that I can't fathom.
Those errors are:
1084: Syntax error: expecting rightparen before _.
1086: Syntax error: expecting semicolon before rightparen.
When I try to correct them, I get new errors. I can't determine whether the sound file is loading; it certainly never plays. The volume slider does not work.
I did find one line that looked like it should have been commented out, the one that reads
to start at the same place
So I tried commenting that out. No dice. Same errors.
Thanks in advance for any suggestions. Code follows:
var musicPiece:Sound = new Sound(new URLRequest _
("http://blog.0tutor.com/JeffWofford_Trouble.mp3"));
var mySoundChannel:SoundChannel;
var isPlaying:Boolean = false;
to start at the same place
var pos:Number = 0;
play_btn.addEventListener(MouseEvent.CLICK, play_);
function play_(event:Event):void {
if (!isPlaying) {
mySoundChannel = musicPiece.play(pos);
isPlaying = true;
}
}
pause_btn.addEventListener(MouseEvent.CLICK, pause_);
function pause_(event:Event):void {
if (isPlaying) {
pos = mySoundChannel.position;
mySoundChannel.stop();
isPlaying = false;
}
}
stop_btn.addEventListener(MouseEvent.CLICK, stop_);
function stop_(event:Event):void {
if (mySoundChannel != null) {
mySoundChannel.stop();
pos = 0;
isPlaying = false;
}
}
var rectangle:Rectangle = new Rectangle(0,0,100,0);
var dragging:Boolean = false;
volume_mc.mySlider_mc.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
function startDragging(event:Event):void {
volume_mc.mySlider_mc.startDrag(false,rectangle);
dragging = true;
volume_mc.mySlider_mc.addEventListener(Event.ENTER_FRAME, adjustVolume);
}
function adjustVolume(event:Event):void {
var myVol:Number = volume_mc.mySlider_mc.x / 100;
var mySoundTransform:SoundTransform = new SoundTransform(myVol);
if (mySoundChannel != null) {
mySoundChannel.soundTransform = mySoundTransform;
}
}
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
function stopDragging(event:Event):void {
if (dragging) {
dragging = false;
volume_mc.mySlider_mc.stopDrag();
}
}
Syntax errors are just what it says they are, the code is not properly written. For instance , you shouldn't have an underscore after URLREquest
var musicPiece:Sound =
new Sound(new URLRequest("http://blog.0tutor.com/JeffWofford_Trouble.mp3"));
to start at the same place should be commented out, simply because it's a comment, it's not a variable or a function.
to call a function "play_" is not really good practice either. Call it soundPlay, if you're concern about conflicts.
same comment for pause_ and stop_

Resources