Difference between revisions of "Legacy:GetTime"

From Spherical
Jump to: navigation, search
(created from http://web.archive.org/web/20110802085151/http://www.spheredev.org/wiki/GetTime)
 
(No difference)

Latest revision as of 22:46, 1 June 2013

Obtains the number of milliseconds elapsed since an arbitrary time.

Usage

integer GetTime();


Examples

var time = GetTime();

The above gets the number of milliseconds passed since some predetermined time, and places it in the time variable.

var start_time = GetTime();
// Code that needs to be timed
// ...
var duration = GetTime() - start_time;

The above example will find out how long a particular piece of code runs for.

function Delay(ms)
{
  var start = GetTime();
  while (GetTime() - start < ms);
}

The above function is a simple mechanism to pause script execution for a given number of milliseconds, called using, for example, Delay(1500);, which pauses script execution for one and a half seconds. No updating or redrawing will take place while the delay is occurring.

var done = false;
var fps = GetFrameRate();
var updates_performed = 0;
var start_time = GetTime();
while (!done)
{
  while (updates_performed < (GetTime() - start_time) * 0.001 * fps)
  {
    // Update game here
    // ...
    updates_performed++;
  }
  // Draw the game screen here
  // ...
  FlipScreen();
}

The above example is one way to regulate the speed of a Sphere game inside a JavaScript loop. The game code will have to be separated into updates (player input processing, moving entities, checking collisions, etc.) and drawing (drawing sprites, the map, score, etc.).

var FPS = 60;             // The desired FPS
var delayTime = 1000/FPS; // The time between frames
var lastTime = GetTime(); // The time of the last frame
while(loopCondition)      // While we should continue looping
{
  if(GetTime() > lastTime + delayTime) // If enough time has elapsed
  {
    lastTime = GetTime(); // Record the time of this frame
    doStuff();            // Do your stuff
  }
  drawStuff();            // Draw your stuff
}

This example is an alternative to the one above. Obviously, doStuff() and drawStuff() will correspond with functions that actually process the game logic and draw the game state respectively.

Notes

  • The starting time can be assumed to be constant throughout the running of a game. Thus GetTime() is very useful as a tool to pace JavaScript loops, which would normally run at different speeds on different systems.
  • Core JavaScript provides a similar mechanism via the Date object's Date.getTime() method. This counter, if used with a Date object that reflects the current time, displays the number of milliseconds since midnight 01 January, 1970 UTC. Refer to the links for more information.
  • Because GetTime() is a signed integer, it will wraparound from time to time.

See also

API:Script/navbox