How to make a timer and make it count backwards

This did not work for me because it was lagging and what I mean by that is that sometimes it went slower than what seconds go, and sometimes it went faster than what seconds go

this is preferred

For a backward running Timer, just use ‘-=’ instead of ‘+=’ in the function ‘timerAdd’ (and maybe you should name the function ‘timerSubtact’ or something like that).

Now you just need to change the start values of ‘project.timerValue’ and ‘end’.

Here’s the Code:

project.timerValue = 10;

window.setTimeout(timerAdd, 1000, project, 0);
// window.setTimeout(function, ms, object, end);
// 1000ms = 1s

function timerAdd (obj, end) {
    obj.timerValue -= 1;
    if (obj.timerValue < end) {
        window.setTimeout(timerAdd, 1000, obj, end);
    }
}

I’m not sure if setTimeout is the best thing to use, because setTimeout will freeze the project until the timeout is over.

i think a better way would be to count the number of frames. every frame, subtract 1 from a variable, and when it hits 0, one second has passed and subtract 1 from the timer and reset your other variable. (i might make an example later, or someone else can.)

1 Like

I prefer using the project fps in order to create a timer
(I’ll explain the steps, it’s easy to use)

Here are steps for doing so:

First

Default Script

Set a variable to the number of seconds you want the timer to start at.
The second variable will be the value of the first multiplied by the fps.

window.seconds = 59;
window.secondsFPS = (seconds * project.framerate)+0.5;

Second

Update Script

In the update script, subtract 1 from the secondsFPS variable, and set timer to secondsFPS divided by the fps of the project.

secondsFPS--;
seconds = Math.round(secondsFPS/project.framerate);

Third

There’s no third step, you’re done :white_check_mark:
Yes, it’s that simple. All you need to do now is use setText to display the value of “seconds” in a text object.


(Also, I added the 0.5 because the timer would be off by 0.5 seconds since it’s being rounded)

2 Likes

I already tried this but I will be trying Hamzah_Al_Ani’s example

Thank you @Hamzah_Al_Ani the example you provided worked well! though I have to say that sometimes it went a little slower than what seconds go but only a little.

2 Likes