Countdown Timer

Hi, I am trying to create a countdown timer but struggling to find/implement a successful code. I want it to start from 2 minutes and 30 seconds and countdown every second until it reaches 0. Any help would be appreciated as I am new to Phaser.

2 Likes

hi,

check this : https://labs.phaser.io/view.html?src=src/time\timer%20event.js

Have a good day.

1 Like

thank you, I have looked at that specific code already however I cannot seem to get the minutes to work, any ideas on how I would edit that code to make it start from 2:30seconds and count down?

Hi @Faizan_Ali,
You can try something like this (Phaser example modified):

var config = {
    type: Phaser.CANVAS,
    width: 800,
    height: 600,
    backgroundColor: '#2d2d2d',
    parent: 'phaser-example',
    scene: {
        create: create
    }
};


var text;
var timedEvent;

var game = new Phaser.Game(config);

function create ()
{
    console.log('create');
    // 2:30 in seconds
    this.initialTime = 150;

    text = this.add.text(32, 32, 'Countdown: ' + formatTime(this.initialTime));

    // Each 1000 ms call onEvent
    timedEvent = this.time.addEvent({ delay: 1000, callback: onEvent, callbackScope: this, loop: true });
}

function formatTime(seconds){
    // Minutes
    var minutes = Math.floor(seconds/60);
    // Seconds
    var partInSeconds = seconds%60;
    // Adds left zeros to seconds
    partInSeconds = partInSeconds.toString().padStart(2,'0');
    // Returns formated time
    return `${minutes}:${partInSeconds}`;
}


function onEvent ()
{
    this.initialTime -= 1; // One second
    text.setText('Countdown: ' + formatTime(this.initialTime));
}

Regards.

4 Likes

Thank you so much

@jjcapellan could you help me on my post :blush: ?
How to enable multitouch ? jsfiddle inside

1 Like

The timer stops if the tab is changed or if the window is minimized, how can we handle this ?

Regards,
Munib Mir

1 Like

Hi,
In your case you need to use hidden and visible events of the game object.
Something like this:

// In your scene.create() function 
this.hiddenTimeStamp = 0;
this.game.events.on('hidden', () => {
    this.hiddenTimeStamp = performance.now();
    });

this.game.events.on('visible', () => {
    let elapsedTime = Math.floor((performance.now() - this.hiddenTimeStamp)/1000); //seconds
    this.initialTime -= elapsedTime;
    })
//...
1 Like

A simple way to do this is to create a timer event with a very long delay and no callback, then read its getRemainingSeconds().

you saved my day…!