Timer API v7 - nodeGame/nodegame GitHub Wiki

  • status: complete
  • version: 7.x

Overview

The Timer API is a subset of the Client API and it is used to create new game timers, measure the time passed between two events, randomly fire events, etc.

Using the Timer API

Creating Timers

The object node.timer contains all the methods of the Timer API and instantiates new GameTimer objects.

A GameTimer is a configurable object to measure time lapses, time differences, and to fire events at a specific moment in time.

GameTimers pause automatically whenever the game is paused and resume automatically when the game is resumed.

To create a new GameTimer use the method createTimer or its alias create.

Examples

Create a timer that will fire the default "TIMEUP" event after 10 seconds.

var timer = node.timer.create(10000);
// Timers do not start automatically.
timer.start();

// Anywhere in the game code you can listen to the "TIMEUP" event.
node.on("TIMEUP", function() {
    alert("Time is up!");
});

To change the default event, pass a configuration object with the timeup and milliseconds properties.

node.timer.create({

    // Timer expires after 10 seconds.
    milliseconds: 10000,

    // Event to fire or function to execute at timeup.
    timeup: 'TIMER_DONE'
})
.start();

To create a recurrent timer that fires periodically, specify the update and hooks parameters.

var timer = node.timer.create({

    // Timer expires after 10 seconds.
    milliseconds: 10000,

    // Every second the hooks are executed/fired.
    update: 1000,

    // An array of events or functions to fire at every update.
    hooks: [

        // Update functions receive the number of milliseconds left and a
        // reference to the game timer itself as input parameters.
        function(timeLeft, timer) {
            console.log((timeLeft/1000) + " seconds to go.");
        },

        // It is possible to specify the context of execution of a hook.
        {
            hook: function(timeLeft, timer) {
                console.log("Hello " + this.name + "! You have " +
                            (timeLeft/1000) + " seconds left.")
            },
            ctx: {
                name: 'Mickey'
            }
        },

        // This event is fired every second.
        'ONE_SECOND_PASSED'
    ]
});
// Timers do not start automatically.
timer.start();

// Anywhere in the game code you can listen to the "ONE_SECOND_PASSED" event.
node.on("ONE_SECOND_PASSED", function(timeLeft, timer) {
    console.log((timeLeft/1000) + " seconds to go.");
});

You can force an early timeup with the method doTimeUp.

var timer = node.timer.create(10000);
// Timers do not start automatically.
timer.start();
// Expire the timer early.
timer.doTimeUp();

Other Timer operations

After a timer has been created the following methods are available to control its behavior:

  • stop: stops and clear timer (resuming not possible, restart required),
  • pause: pauses timer (resuming possible),
  • resume: resumes a paused timer,
  • init: inits a stopped timer (without starting it),
  • restart: restarts a stopped timer (inits and starts it).

setTimeout

The setTimeout is a shortcut to create and start a game timer with the same syntax of the JavaScript setTimeout method.

node.timer.setTimeout(function() {
    console.log("Time expired!")
}, 10000);

Using the method from the Timer API instead of the native JS setTimeout has two advantages:

  • the timeout is automatically paused and resumed when the game is paused and resumed,
  • the timeout is tied to the step in which it is created and automatically disposed if the step is terminated earlier (see next section Timer validity).

Timer validity

Timers are valid only within the step in which they are created. This means that, regardless of whether the timer expired or not, the timer will be disposed when entering the next step.

To change the default behavior and extend the life of a timer across steps use the validity flag.

node.timer.create({
    milliseconds: 10000,
    // Keeps the timer alive through all the steps of the current stage.
    validity: 'stage'
})
.start();

// With the setTimeout syntax.
node.timer.setTimeout(function() {
    console.log("Time expired!")
}, 10000, 'stage');

Accepted values for validity are:

  • ng: as long as nodeGame is running (across games)
  • game: the entire game (across stages)
  • stage: the entire stage (across steps)
  • step: current step (default).

Retrieving Timers

To retrieve a timer for which you no longer have a direct reference you need to name it and then use the method node.timer.getTimer.

var timer = node.timer.create({

    name: 'myName',

    milliseconds: 10000
})

timer.name; // myName

// Retrieving the timer by name.
var timer2 = node.timer.getTimer('myName');
timer2.name; // myName

Alternatively, timers can be retrieved from the node.game.timer.timers collection.

Destroying Timers

The following methods are available to destroy timers (cannot be undone):

  • node.timer.destroyTimer(timer): a given timer,
  • node.timer.destroyStepTimers(): all timers with validity current step,
  • node.timer.destroyStageTimers(): all timers with validity current stage,
  • node.timer.destroyAllTimers(): all timers (use with caution!).

Setting Timestamps and Measuring Time Differences

It is possible to timestamp specific events using the command setTimestamp and choosing a name for it.

node.timer.setTimestamp('mytimestamp');

The command optionally takes a second parameter to set the timestamp to a specific time, rather than (new Date()).getTime().

To retrieve a timestamp later, use the command getTimestamp with the name of chosen timestamp, or getAllTimestamps to get them all in an object.

node.timer.getTimestamp('mytimestamp');

To measure time differences the following methods are available:

// Time passed since a timestamp was defined.
node.timer.getTimeSince('mytimestamp');

// Time interval between two timestamps.
node.timer.getTimeDiff('mytimestamp', 'mysecondtimestamp');

Automatic Timestamps

The following timestamps are automatically created:

  • start: time since the game has been started
  • paused: time since the game has been paused for the last time
  • resumed: time since the game has been resumed for the last time
  • stage time since the game entered in the current stage
  • step: time since the the game entered in the current step

The timestamps above are overwritten every time the same event happens while the game is executed. For instance, the 'step' timestamp is overwritten at every new step.

However, the timestamp related to each specific 'step' are kept under the name or the id of the step. That is, the timestamp related to the beginning of step 1.1.1 is stored under '1.1.1'.

Random Events

To fire an event or execute a callback at random within a certain time interval you can use the node.timer.random(minWait, maxWait) method and chain the appropriate handler:

  • emit: emits an event,
  • exec: executes a callback,
  • done: calls node.done,
  • timeup: calls node.timer.doTimeup.

For instance:

// Emits the event 'MY_EVENT' randomly in the next 20 seconds.
node.timer.random(20000).emit('MY_EVENT');

// Emits the event 'MY_EVENT' randomly between the next 10 and 20 seconds.
node.timer.random(10000, 20000).emit('MY_EVENT');

Defaults

The default value of minWait is 1000 and maxWait is 5000, so the following code will randomly emit an event between 1 and 5 seconds.

node.timer.random().emit('MY_EVENT');
// Or even shorter.
node.timer.random.emit('MY_EVENT');

Exact waiting time

The wait method is equivalent to having a random timer with where minWait and maxWait are the same.

// Equivalent to node.timer.random(20000, 20000).emit('MY_EVENT');
node.timer.wait(20000).emit('MY_EVENT');

Probabilistic events

It's possible to add a probability that an event will fire, a function will be executed, etc. with the prob method.

// With probability 0.5, the event is fired randomly in the next 20 seconds.
node.timer.random(20000).prob(0.5).emit('MY_EVENT');

If the probability to fire is not known in advance, a function can be specified as a parameter to prob.

node.timer.random(20000).prob(function() {
    // Condition probability on current score in the game (0-1).
    // Higher scores have lower probability to fire here.
    return Math.random() > node.game.score;
}).emit('MY_EVENT');

API

Timer methods

  • createTimer|create
  • destroyTimer
  • destroyStepTimers
  • destroyStageTimers
  • destroyAllTimers
  • setTimestamp
  • getTimestamp
  • getAllTimestamps
  • getTimeSince
  • getTimeDiff
  • getTimer

GameTimer Class

  • init
  • fire
  • start
  • addHook
  • removeHook
  • pause
  • resume
  • stop
  • restart
  • isRunning
  • isStopped
  • isPaused

See Also

⚠️ **GitHub.com Fallback** ⚠️