Forum Discussion

Jenn-Barnabee's avatar
Jenn-Barnabee
Community Member
6 days ago

JavaScript Timer Question

Hello! I'm new to using JavaScript in Storyline. But after watching a Learning Dojo video and using Claude to help me put some code together, I was able to come up with the following code to use in an "execute JavaScript" trigger that happens when the learner clicks the Start button for a matching game. My goal is to start a timer when they start the game. It counts in seconds and shows on the screen as they go through the game. When the learner completes the game, it shows them how many seconds it took them. All of that works one time. But if the learner clicks to restart the game, the original timer is still counting from the first go-around, plus a new timer is started, such that it flashes back and forth between one counter and the other. I can't figure out how to stop the timer, reset it, and allow them to start over. Claude suggested the code where it "clears any existing timerId stored in Storyline" -- but while a new timer starts, the old one still keeps going.  Is there any solution to this? Thanks for any help!

//Getting the player
const player = GetPlayer();

//Where to start
let sec = 0;

//Set up the timer
function startTimer() {
    sec += 1;
    player.SetVar("timer", sec);
}

//Clear any existing timerId stored in Storyline
let existingTimerId = player.GetVar("timerId");
if (existingTimerId !== null && existingTimerId !== undefined) {
    clearInterval(existingTimerId);
}

//Reset the counter
sec = 0;
player.SetVar("timer", sec);

//Start the timer and store the ID in Storyline
let timerId = setInterval(startTimer, 1000);
player.SetVar("timerId", timerId);

2 Replies

  • Nedim's avatar
    Nedim
    Community Member

    Please check the attached Storyline file. Although I usually prefer playing games on their native platforms rather than within authoring tools, I took the time to create a simple solution that may help you track game time effectively.

    This setup includes a JavaScript timer that you can start, pause, and reset as needed. The main JavaScript code loads when the timeline starts. After that, you can control the timer by calling functions such as gameTimer.start(), gameTimer.pause(), and gameTimer.reset(). These functions can be triggered from buttons or other Storyline events.

    In addition to that, I created a timerId variable, which I believe aligns with your original approach based on your script. The code ensures that a new timerId is generated each time the user clicks the start button. When the reset function is called, the timerId is cleared as well, so that a new timerId will be created the next time the start button is pressed. 

    Example:

  • Thank you so much, Nedim! I will see if I can adopt this into my game. Much appreciated!!!