Displaying a timer in mm:ss format online (optimization)

Hello everyone,

in my online experiment I had to present a timer on screen in the mm:ss format (mm = minutes, ss = seconds). While i had no problem coding It using phyton I had some problem with Javascript. I have written this code:

In the begin routine tab:

timer_tutorial_s = new util.Clock();
timer_tutorial_m = new util.Clock();
timer_tutorial_m.add(29.5);

tutorial_timestring = "00:00";

In the each frame tab:

tutorial_time_s = timer_tutorial_s.getTime();
tutorial_time_m = timer_tutorial_m.getTime();

tutorial_second = (tutorial_time_s % 60);
tutorial_minute = (tutorial_time_m / 60);

if ((tutorial_second <= 9.5)) {
    second_tutorial_timestring = ("0" + tutorial_second.toFixed(0));
} else {
    if (((tutorial_second > 9.5) && (tutorial_second < 10))) {
        second_tutorial_timestring = "10";
    } else {
        if (((tutorial_second >= 10) && (tutorial_second <= 59.5))) {
            second_tutorial_timestring = tutorial_second.toFixed(0);
        } else {
            if (((tutorial_second > 59.5) && (tutorial_second < 60))) {
                second_tutorial_timestring = "00";
            }
        }
    }
}


if ((tutorial_minute < 0.4917)) {
    minute_tutorial_timestring = "00";
} else {
    if (((tutorial_minute >= 0.4917) && (tutorial_minute < 9.4917))) {
        minute_tutorial_timestring = ("0" + tutorial_minute.toFixed(0));
    } else {
        if ((tutorial_minute >= 9.4917)) {
            minute_tutorial_timestring = tutorial_minute.toFixed(0);
        }
    }
}


tutorial_timestring = ((minute_tutorial_timestring + ":") + second_tutorial_timestring);

And then there is a text component with $tutorial_timestring as text, set tu update every frame.

Although the code seems to be working I wonder if someone has any suggestion to improve It, maybe using less line of code.

Thank you,
tandy

hi @tandy,

I want to create a timer as well. I’ve seen you code is working but I don’t undesrtand what you did as I’m pretty new to programming in general. Would you mind explaining your code?

Thanks!!

I use:

newTime = (exptTime - timeStart.getTime());
if ((newTime < 0)) {
    newTime = 0;
}
mins = Math.floor((newTime / 60));
secs = (newTime % 60);
if ((newTime !== oldTime)) {
    clock_time.text = ((Number.parseInt(mins).toString().padStart(2,"0") + ":") + Number.parseInt(secs).toString().padStart(2,"0"));
  oldTime = newTime;
}

The first block is auto translated from Python but the second needs a Both component. The Python version is:

if newTime != oldTime:
    clock_time.text=str(int(mins)).zfill(2) + ':' + str(int(secs)).zfill(2)
    oldTime = newTime

1 Like

Hi Viviana, I suggest using @wakecarter code instead of mine :smiley:

I’ve decided to use this example as a starting point for a new companion document to my crib sheet – PsychoPy Code Component Snippets.