Performing animation using the JavaScript setInterval(…) function

The setInterval(…) function is still popular on the Web, and even though this is not the recommended way to do 60 frames/second canvas animation, it is worth understanding how it works.

BASIC EXAMPLE THAT SHOWS HOW TO ANIMATE A DIV USING THE DOM API (THIS IS HOW PRE-HTML5 GAMES WERE WRITTEN)

Please try it online: http://jsbin.com/huluhe/2/edit (open the html, JavaScript and output tabs)

Animate the monster in a canvas, using setInterval

Online example: http://jsbin.com/lomopo/1/edit

PROBLEMS WITH SETINTERVAL

Running several animations simultaneously

The setInterval function may become hard to debug, particularly if you run several animations simultaneously. For example, if you have two intervals, one running every 100 milliseconds, the other every second, and if you want to debug the second one, the first one will constantly be run at regular intervals, making step by step debugging really difficult.

A single animation may be interrupted by itself to become two simultaneous animations

setInterval will execute the function passed as first parameter every n milliseconds regardless of when the function was last called or how long the function takes to execute. If the function takes longer than the interval, then setInterval might queue too many function executions back to back when the interval is too short, leading to unpredictable results.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s