pomcom icon

The setTimeout() function.

setTimeout(function,delay)

The setTimeout function is used to call a function after a certain period of time (in milliseconds) has passed.
Each function that made a stroke, a fill, or a fade on this example was called on a delay using the setTimeout function.

Is it easy enough for me to do?

Sure it is! The same concept in this tutorial example, using setTimeout() to increase the width of the rectangle by 5 pixels every 100 milliseconds, can be used to create a plethora of fantastic animations even better than those on this page.

Follow along with the code snippet!

screenshot of the code used in explanation for reference

...or download the full source file. (If it opens in a new window in your browser you will have to manually save it.)

There's a few easy steps to it.

  1. (line 12) Declare a variable to manipulate.
  2. (line 14) Create a function that will be called repeatedly. In this example, drawRect (line 16) increases rectW causing the rectangle to be wider. When it has reached 395 pixels (line 18), it resets to 5 pixels(line 20). The screen is then cleared (line 23) and the rectangle is drawn (line 25). On line 27, the setTimeout function calls drawRect after a 100 millisecond delay.
  3. Finally, like on line 30, none of this will happen if you don't call drawRect to get it started.

a few more setTimeout() examples

pomcom icon