Time for Animation!

 

 

Lonce Wyse

Communication & New Media

lonce.wyse@cnm.nus.sg

Date (time)

  • Bullet One
  •  
// milliseconds since Jan 1, 1970!
var then_in_ms = Date.now();

{ ... do something that takes some time ... }

var now_in_ms = Date.now();

var duration = now_in_ms - then_in_ms;

Timer events (one-off)

  • Bullet One
  •  
// structure: 
setTimeout( function, milliseconds);

//example
setTimeout( function(e){ alert("Yo time!");}, 1000); // 1000ms = 1 second

Timer events (periodic)

  • Bullet One
  •  
// structure: 
// repeatedly call the function
var myTicker = setInterval( function, milliseconds);   

//and to stop the madness:
clearInterval( myTicker );  // Stop the periodic callbacks

What can we do with this?

Animation!

Timer counting example

  • Bullet One
  •  
var tcounter = 0;      // outside callback function

var myTicker = setInterval( function(){
          tcounter++;  // same as: tcounter = tcounter +1
          console.log("Ticker count is " + tcounter);
          if (tcounter >= 10) { clearInterval(myTicker);}
    }, 1000);          // 1000 ms is one second

Math object 

Math.PI
Math.SQRT2
 
Math.abs(x)    -  |x|
Math.pow(x, y) -  x^y


Math.cos(x)   - Returns the cosine of a number.
Math.sin(x)   - Returns the sine of a number.


Math.ceil(x)  - Returns the smallest integer greater than or equal to a number.
Math.floor(x) - Returns the largest integer less than or equal to a number.
Math.round(x) - Returns the value of a number rounded to the nearest integer.

Math.max(x,y, ...)  -  Returns the largest of zero or more numbers.
Math.min(x,y, ...)  -  Returns the smallest of zero or more numbers.

Math.random() - Returns a pseudo-random number between 0 and 1.

Built in for your convenience

Math object Example

Want: function to generate random number in [m, n]

Math.random() gives a number in [0,1)

var randInt = function( m, n ) {
    var range = n-m;
    var frand = Math.random()*range;
    return m+Math.floor(frand);
}

(m) ....... (m+1)                      ....... (n-1)     ....... (n) 

[                                 )

Math.floor

Math.random

[                                                     )

004.001.xxx_Timers and the Math object

By lonce

004.001.xxx_Timers and the Math object

A brief overview of audio synthesis fundamentals, and how to create interactive audio on the Web.

  • 975