Forum Discussion
Stop / reset JavaScript in a storyline
After about 15 hrs of chatgpt helping me write code I've got something that works!
function zeros(num) {
if (num < 10) {
return "0" + num;
}
return num;
}
var player = GetPlayer();
var count = 20; // Set the countdown duration to 20 seconds
var timerID = player.GetVar("Timer_ID"); // Retrieve the stored timer ID
function startTimer() {
timerID = setInterval(timer, 1000);
player.SetVar("Timer_ID", timerID); // Store the timer ID in a Storyline variable
}
function stopTimer() {
clearInterval(timerID);
}
function resetTimer() {
stopTimer(); // Stop the previous timer
count = 20; // Reset the countdown duration to 20 seconds
var minutes = zeros(Math.floor(count / 60));
var seconds = zeros(count % 60);
var totalTime = minutes + ':' + seconds;
player.SetVar("Countdown_Display", totalTime);
player.SetVar("Timer_finished", 0);
startTimer(); // Start the new timer
}
function timer() {
if (player.GetVar("Reset_Timer") === 1) {
resetTimer();
player.SetVar("Reset_Timer", 0); // Reset the player variable
return;
}
count = count - 1;
var minutes = zeros(Math.floor(count / 60));
var seconds = zeros(count % 60);
var totalTime = minutes + ':' + seconds;
player.SetVar("Countdown_Display", totalTime);
if (count <= 0) {
player.SetVar("Timer_finished", 1);
stopTimer(); // Stop the timer when countdown is finished
}
}
// Clear the previous interval timer if the stored timer ID is valid
if (timerID) {
clearInterval(timerID);
}
// Initial setup
resetTimer(); // Call the resetTimer() function initially to set up the countdown
// Example usage: Set the player variable "Reset_Timer" to 1 to reset the timer
player.SetVar("Reset_Timer", 1);
It works thank you so much!