Javascript Countdown Timer

Sep 24, 2021

Hello heroes!

I'm trying to create a Javascript countdown timer that starts at 02:30:00 and when the remaining time is over, the course is complete.

However, i'm facing this problem: everytime the learner refreshes the browser tab or leaves the course, the timer either stops or restart the count. What I need is: even if the page is refreshed, the timer continues to count down. Is it possible?

Can I use cookies to storage the values? If positive, how can I do that?

Javascript masters can help me, please?

Here's my code (I'm super newbie to JS, sorry if my code is bad):

 

------

var player = GetPlayer();

// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setMinutes (countDownDate.getMinutes() + 150);

// Update the count down every 1 second
var x = setInterval(function() {

// Get today's date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var hh = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
player.SetVar("hours", hh);
var mm = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
player.SetVar("minutes", mm);
var ss = Math.floor((distance % (1000 * 60)) / 1000);
player.SetVar("seconds", ss);

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
return;
}
var totalTime = hh + ':' + mm + ':' + ss;
player.SetVar("Countdown_Display",totalTime);
}, 1000);

------

If it helps, my story file is attached too. I'm manupulating everything by the slide master.

4 Replies
Math Notermans

Testing your Story... the variable 'count_start' needs to be set to 'false' when the timer is running. This is not happening now. So if you do that...it keeps counting nicely whenever you change tabs. But it is not fixed completely with this. Do add a 
console.log("totalTime: "+totalTime+" | count_start: "+player.GetVar("count_start"));
in your Javascript when the countdown is over. Then you will notice that however the count keeps counting down nicely...the variable 'count_start' gets reset to 'True' whenever a new questions starts. So this we need to fix still.

Math Notermans

So by adding a new variable... isCountdownStarted... and setting that to true at start... and adding a condition when setting the variable 'count_start' to True...we ensure the timer wont be reset when continuing to a next question. In the Javascript ofcourse we set 'isCountdownStarted to false the moment the countdown starts. So now it wont reset at each question.

What still needs fixing is the resume behaviour. I set all slides including the question bank to 'Resume Saved State' but we now still need to make sure the variables for the duration will be changed so when resuming... it wont use the static variables as is now.