Wednesday, September 8, 2010

All about intervals in AS3

Today we will learn all about intervals, which can be very useful in your flash applications and games.

Basically, setInterval is a simple version of the Timer class. You set the delay time in milliseconds and an action to commence. SetInterval works only with functions. Here is an example:

function sayHi():void{
trace("hi!");
}
setInterval(sayHi, 500);

The code above will trace "hi!" every half a second. It will never stop. You can use an unnamed function inside the setInterval method too, if it is a simple one:

setInterval(function(){trace("hi!");}, 500);

Same results as the previous example.

If we have parameters in our function, for example, a String variable that gets traced by the function, we can pass the parameter through setInterval.

function say(tex):void{
trace(tex);
}

setInterval(say, 1000, "hello!");

// The line below will NOT work:
// setInterval(say("hello!"), 1000);

These intervals will never stop. However there is a method called clearInterval, which stops the setInterval method from going. However, clearInterval only works with intervals stored in variables, that means we have to turn our interval into a variable. We can put the clearInterval method in our function, making it only commence once.

function sayHi():void{
trace("hi!");
clearInterval(myInt);
}

var myInt = setInterval(sayHi, 1000);

Hope this was helpful. Thanks for reading!

Related:

All about Timer class

No comments:

Post a Comment