views:

16

answers:

2

Hi. So i have this function

capture_mc.buttonMode = true;
capture_mc.addEventListener(MouseEvent.CLICK,captureImage);

function captureImage(e:MouseEvent):void { 
//lalalala

}

I want to call this function every 2 seconds (after mouse click event happens). I tried using setInterval

setInterval(captureImage,2000,e:MouseEvent);

but it leads to following error

1084: Syntax error: expecting rightparen before colon.

What's wrong ? And ya, i am new to AS.

+2  A: 

First, since this is AS3 you should be using Timer and TimerEvent. I'll show you how in the example.

Now you'll need to separate your functions:

edit: I've updated this to be safer based on @(Juan Pablo Califano) suggestions. I would keep the same timer for ever if the amount of time isn't going to change.

// first param is milliseconds, second is repeat count (with 0 for infinite)
private var captureTimer:Timer = new Timer(2000, 0);
captureTimer.addEventListener(TimerEvent.TIMER, handleInterval);

function handleClick(event:MouseEvent):void
{
    // call here if you want the first capture to happen immediately
    captureImage();

    // start it
    captureTimer.start();
}

function handleInterval(event:TimerEvent):void
{
    captureImage();
}

function captureImage():void
{
    // lalalala
}

You can also stop the timer with captureTimer.stop() whenever you want.

James Fassett
Thanks a lot :)
Anil Dewani
+1. It would also be a good idea to check whether your timer is running at the top of `handleClick`, and perhaps bailing out if it's running (or reseting the timer if that makes sense given the context). This could be implemented with a simple boolean flag or checking if `captureTimer` is not null. Otherwise, you could end up with multiple timers running and you won't have a way to stop them (because you'd be losing the reference to the old ones when you assign a new `Timer` object to the `captureTimer` variable.
Juan Pablo Califano
+1  A: 

The problem is that you should use the parameterName:ParameterType syntax only when declaring formal parameters (or when declaring vars and consts). Meaning, this is valid only when you are defining a function:

function func(paramName:Type){
}

When you call the function, you don't have to put the type of the arguments.

So, your function call should look like this:

setInterval(captureImage,2000,e);
Juan Pablo Califano