search

Class myphysicslab.lab.util.Timer

Provided By

Periodically executes a callback function; Timer is a fancier version of JavaScript's setInterval() function.

Chain of Callbacks

Timer has a single callback function which is intended to repeatedly execute or 'fire'. To keep the chain of callbacks going each callback must reschedule itself to execute again in future by calling #fire, #fireAfter or #finishAt.

Once the callback has been specified via #setCallBack, the chain of callbacks is started by calling #startFiring.

Here is some example code showing how to use a Timer, from BlankSlateApp

var r = PointMass.makeSquare(4);
var dr = new DisplayShape(r);
displayList.add(dr);
dr.strokeStyle = 'red';
var clock = new Clock();
var timer = new Timer();
var callback = function () {
    r.setAngle(Math.sin(clock.getTime()));
    simCanvas.paint();
    timer.fireAfter();
};
timer.setCallBack(callback);
clock.resume();
timer.startFiring();

You can try that code out by pasting it into the Terminal on the BlankSlateApp example page.

Timing of Callbacks

The method #fireAfter schedules the callback to run after a short delay. The method #finishAt schedules the callback to finish at a specified time. Both these methods take into account how late the current callback is and how long it took to execute in deciding when to schedule the callback to fire.

Here is an example of how using the 'lateness of the current callback' can result in smoother animation: Suppose we want to draw a frame every 50 milliseconds, and on newer machines it takes essentially zero time to compute the next frame. Suppose that on older machines it takes 10 milliseconds to compute the next frame. If (at the conclusion of the callback) we simply schedule the next callback to happen in 50 milliseconds, then we achieve the desired frame rate on new machines, but on older machines, the frame period is a slower 60 milliseconds. If we consider the 'lateness' and ask for a delay of 40 milliseconds on the older machines they would also achieve a 50 millisecond frame period.

A similar story applies when the compute load varies over time on a machine. When the compute load is heavier, we need to shorten the delay between callbacks to maintain a given frame rate.

The 'lateness' of the current callback is derived from #getExpectedTime.

new Timer()

Parameters

None.

Instance Methods