- the new global functions setInterval() and clearInterval() provide javascript-like tools for timed execution of code.
- setInterval() runs a function or method every n milliseconds.
// Create a function to run after a countdown.
function helloWorld () {
trace("Hi!");
}
// Call helloWorld() every 50 milliseconds.
setInterval(helloWorld, 50);
- Same thing, but with a function literal:
// Call function literal every 50 milliseconds.
setInterval(function () { trace("Hi!"); }, 50);
- Method version of setInterval():
// A method on the ball movie clip.
ball.move = function (xAmount, yAmount) {
this._x += xAmount;
this._y += yAmount;
// Refresh the screen if the interval runs
// faster than the framerate.
updateAfterEvent();
}
// Call ball.move() every 50 milliseconds, passing
// the arguments 1 (xAmount) and -2 (yAmount).
// Arguments are only evaluated once.
setInterval(ball, "move", 50, 1, -2);
- A countdown that stops an interval from repeating endlessly:
// Create a function to run after a countdown.
function timesUp () {
trace("Time's up!");
// Stop the timer.
clearInterval(timerInterval);
}
// Call timesUp() after 5000 milliseconds.
// Store the interval ID in a variable so we can stop the interval.
timerInterval = setInterval(timesUp, 5000);