Using the setTimeout() JavaScript function

Using setTimeout() instead of setInterval()

INTRODUCTION

One thing you should always remember about using setInterval: if we set number of milliseconds at – let’s say 20ms – it will call our game loop function EACH 20ms, even if the previous one is not yet finished. This may lead to many problems (incomplete rendering, etc.).

That’s where we can use another function:

    • Syntax: setTimeout(function, ms);

This function works like setInterval(…) with one difference: it calls your function ONCE and AFTER a given amount of time.

EXAMPLE OF THE MONSTER ANIMATED IN A CANVAS WITH SETTIMEOUT

Example of use: http://jsbin.com/timebu/3/edit (open the JavaScript, console and output tabs).

PROBLEMS WITH SETINTERVAL() AND SETTIMEOUT()

setTimeout does not “wait”  during the timeout period. It lets the rest of the JavaScript code run. It schedules a new call to the function passed as first parameter with a timer running in the background. This might cause it to take slightly longer than the expected timeout period to start executing.

This problem also occurs with setInterval, the timing is not “very” reliable. If you plan to run a function every 20ms, and if you measure precisely the real timing, sometimes you will discover big differences between what is scheduled and what is performed. This is because these methods were designed a long time ago, when high precision timers and 60 frames per second animation were not an option.

Here comes the requestAnimationFrame API, a very good companion to the canvas API!

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