Introduction to JavaScript Fall 2010 Class 10

esse quam videri
Revision as of 00:20, 10 November 2010 by Matthew.ephraim (talk | contribs)
Jump to: navigation, search

Introduction

This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss anonymous functions, which will be useful when we start using timers.

Anonymous Functions

Anonymous functions are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:

 function() {
   // your code here
 }

Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:

 Behavior.someFunction = function() {
   // your code here
 };

Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass an anonymous function as a parameter to the jQuery click function:

 $("#button-id").click(function() {
   // code for handling the click event
 });

The anonymous function will work exactly the same way this code:

 $("#button-id").click(handleClick);
 
 function handleClick() {
   // code for handling the click event
 }

The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in to the click function.

Anonymous functions will become more useful when we start working with timers.

JavaScript Timers

Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay. Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.

Using a Timer to Delay a Function Call

The first type of timer uses the setTimeout function. The setTimeout function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called myDiv. You could handle it with jQuery like this:

  $('#button-id').click(addParagraph);
 
  function addParagraph() {
     $('#myDiv').append('<p>hello</p>');
  }

You should already be familiar with this kind of thing, because we've done it in class.

However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the setTimeout function to accomplish this.

  // When the button is clicked, create a new timer that will call the
  // addParagraph function after 2 seconds
  $('#button-id').click(function) {
     setTimeout(addParagraph, 2000);
  };
 
  function addParagraph() {
     $('#myDiv').append('<p>hello</p>');
  }

The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. setTimeout will take in the name of a function as the first parameter:

  // Call functionName after 1 second
  setTimeout(functionName, 1000);

Or it will take in an anonymous function that you want to be called:

  // Call the function block after 1 second
  setTimeout(function() {
     // some code you want to be called
  }, 1000);

In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).

Using a Timer to Repeatedly Call a Function

The second type of timer uses the setInterval function. Like the setTimeout function, the setInterval function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:

  // Call myFunction every second
  setInterval(myFunction, 1000);

Or:

  // Call the function block every second
  setInterval(function() {
     // some code you want to  be called
  }, 1000);

What makes setInterval different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.

Stopping Timers

Both setTimeout and setInterval are functions that will wait a number of milliseconds before calling another function. What if you called setTimeout or setInterval, but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?

Stopping setTimeout

When you call the setTimeout function it returns a value you can store in a variable:

 var timer = setTimeout(functionName, 1000);

If you have stored setTimeout's return value you can use that value with another function called clearTimeout. The clearTimeout function will stop the timer from running if it hasn't already run yet.

For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:

  // Create a new timer and store it in the timer variable
  var timer = setTimeout(myFunction, 10000);
  
  ... // whatever other code you might want to go here
  
  // If 10 seconds haven't passed already this will cancel the timer
  // and the function will never get called
  clearTimeout(timer);

In the example above, setTimeout creates a new timer, which gets stored in the timer variable. Later on in the code clearTimeout stops the timer from running. If 10 seconds already have gone by, clearTimeout won't do anything.

Stopping setInterval

Just like the setTimeout function, setInterval returns a timer that you can store in a variable:

  var timer = setInterval(functionName, 1000);

Once you have the timer that setInterval returned, you can use the clearInterval function to stop the timer from running. clearInterval takes in a timer variable and cancels the timer:

  // Create a new timer and store it in the timer variable
  var timer = setInterval(myFunction, 10000);
  
  ... // whatever other code you might want to go here
  
  // Stop the timer from running. This will prevent the
  // timer from calling the function again
  clearInterval(timer);

The clearInterval function will take the timer that his been running and stop it from running again. setInteval repeatedly calls a function until clearInterval stops it from running again.

Today's Interesting JavaScript Site

Processing.js

Activity

From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.

You can download the template for the activity here.


Assignment 5

Due Friday November 19th

Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:

  • It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either setTimeout or setInterval
  • It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.
  • Draw as many elements as you want, but draw at least 3 elements.
  • The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.
  • The elements must change in some way in response to the mouse event. Remember that you can use the attr or animate functions to change the attributes on any Raphael element.

The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the attr or animation functions:

  var circle = canvas.circle(5, 5, 10);
  
  // animate the circle to position x = 20, and y = 30
  circle.animate({ cx: 20, cy: 30 }, 200);
 
  var rect = canvas.circle(100, 100, 10, 10);
  
  // animate the rect to position x = 50, and y = 20
  circle.animate({ x: 50, y: 20 }, 500);

A list of other attributes you can modify is here.

Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:

  var circle = canvas.circle(5, 5, 10);
  
  // change the color of the element when the user clicks on it
  circle.click(function() {
     circle.animate({ fill: '#6DBE9F' });
  });

Remember that you can find documentation and examples at the Raphael site, and you can use the Raphaël page from last week to see how to draw Raphaël elements.

You can also see a list of jQuery's event handlers here under Event helpers. Many of jQuery's helpers have the same names as Raphael's event helpers.

I have posted a sample project that shows you the kind of thing I'm looking for here. You can use it as a starting point if you'd like.

If you have any questions about the assignment let me know.

Final Project

We've covered a lot of topics in the class. I'd like you to create final project that incorporates at least 4 of the topics listed below.

The project is up to you. If you have a project for another class or something at work that could be made better using JavaScript, you are welcome to use it. If you have a personal portfolio that you'd like to make more exciting with JavaScript, that works too. You can also create a simple art project or game.

I'd like you to email your project idea before next week's class. If you are having a hard time coming up with a project, let me know and I can help you figure out something else.

The import thing is: don't panic. I'm not expecting anyone to become a JavaScript genius in this class. Your project can be simple. Just make sure to include at least 4 of the topics listed below.

Your final project will be due Friday December 10th, and you will present your project in class on December 13th.

Topics From This Class