Wednesday, April 28, 2010

Javascript "setTimeout()" Function

I needed to write a portion of the billboard to have information stored and linked to each other. I first thought about having classes, but I originally thought that Javascript was a classless language. After doing some research I found that classes can be imitated in Javascript by using functions. I found a good article on defining a class in Javascript that helped me learn about the Javascript classes. A each of these 'classes' have public and private variables. The public variables are set by using the 'this' keyword while the private variables do not have the keyword.

In this billboard application, I also needed to find a way to have the function call itself and loop. So I decided on using the setTimeout() function. The setTimeout() function actually calls the function after a set amount of time. I originally thought that the code stops at this function then moves on to the next line of code after the function is called, but in actuality, the code is put in the background for a set amount of time then executed when the time is up. This was a big relief as it allowed me to execute each of the individual 'div' portions of the page.

I ran into an interesting problem while working with the setTimeout function. Trying to call a function that has parameters in the setTimeout() function. For example:

setTimeout(foo(parameter1, parameter2,parameter3), 2000);

would not work since the function expects the function that will be called, a comma, then the time (in milliseconds) to wait before the code is executed. So I looked up this problem and learned that I had to use closures in my code. I found a good article about how to use closures. So to get my code running I had to set a variable that holds the function call with the parameters. Using closures, my code looks like the following:

var temp = function() {foo(parameter1, parameter2,parameter3);};
setTimeout(temp, 2000);

Our billboard is now almost complete as it has nice transitions from one of the content to the other. Our billboard for the kukui cup can be found here.

Useful sites I found:
Using Closures:
http://www.lejnieks.com/2008/08/21/passing-arguments-to-javascripts-settimeout-method-using-closures/

Set Interval vs setTimeout:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

Defining a class in Javascript:
http://www.phpied.com/3-ways-to-define-a-javascript-class/

0 comments:

Post a Comment