Simplex Marketplace Simplex Marketplace - 15 days ago 5
HTML Question

Store autogenerated content of div and make it available on page reload

I am currently creating an exam portal which requires a consistent timer on all page navigation and redirect to submission after the time has been exhausted.

Am currently using the native javascript to do the timing and its displayed below

// JavaScript Document

var count = remsecs;
var count2 = remmin;
var count3 = remhrs;
var counter = setInterval(timer, 1000); //1000 will run every 1 second

function timer(){

count = count - 1;

if (count3 > 0){
if (count2 == 0){
count3 = count3 - 1;
count2 = 59;
count = 59;
timer();
//clearInterval(counter); //counter ended, do something here

//count = count - 1;
}
}

if (count == 0){
count2 = count2 - 1;
count = 60;
timer();
//clearInterval(counter); //counter ended, do something here

//count = count - 1;
}

document.getElementById("timerhr").innerHTML = '<strong>' + count3 + "</strong>";
document.getElementById("timermin").innerHTML = '<strong>' + count2 + "</strong>";
document.getElementById("timersecs").innerHTML = '<strong>' + count + "</strong>";

var myhrs = document.getElementById("hrs").value = count3;
var mymin = document.getElementById("mins").value = count2;
var mysec = document.getElementById("secs").value = count;

//document.write(count + "<br />" + count2);

if (mymin <= 3 && mymin > -1 && myhrs == 0){
document.getElementById("timerhr").innerHTML = '<font size="+2" color="red"><strong><blink>' + count3 + "</blink></strong></font>";
document.getElementById("timermin").innerHTML = '<font size="+2" color="red"><strong><blink>' + count2 + "</blink></strong></font>";
document.getElementById("timersecs").innerHTML = '<font size="+2" color="red"><strong><blink>' + count + "</blink></strong></font>";
}
if (mymin == 0 && mysec <= 02 && myhrs == 0){
window.location = "printresult.php";
}
}


Actually, I'm trying to avoid storing the content of the timer div everytime to the database on press of any button on the page.

Is there a simple way to have this timer stored to the browser and it picked from it every time the page reloads?

Thanks

Answer

Have you looked up possible browser storage options? Downside is they're supported only by browsers that support HTML5.

And save the count variable everytime you navigate away from the page.

Depending on your case you could use sessionStorage. You'd have to change your code like so

...
var count = remsecs;
// checks if sessionStorage has an existing examtimer property
if(sessionStorage.hasOwnProperty('examtimer')) { 
  // sessionStorage only stores string to parseInt
  count = parseInt(sessionStorage.examtimer);
}

...
// executes before tab is navigated away or close
window.onbeforeunload = function(){ 
   // saves count into sessionStorage with the key of examtimer
   sessionStorage.setItem("examtimer", count); 
}