I'm writing a script that lets a user know how much time he spent on a page before refreshing it. To this purpose, I increment a time counter with a setInterval function, and store the data in the browser thanks to localStorage. Once the page is refreshed, I retrieve the data stored, and display them. Meanwhile, the time counter goes back to 0 and starts incrementing again.
Unfortunately, something is wrong with my script because localStorage doesn't store the updated time value (it's always -1). What's wrong with my script?
//TimeSpent = -1, so setInterval sets it to 0s instead of 1s when the page opens.
var timeSpent = -1
//Update time every second
var timer = setInterval(()=>{
timeSpent +=1;
}, 1000);
//If first visit, ask to refresh. Else, display timeSpent on previous page by retrieving localStorage data.
function start(){
if (localStorage.timeData){
var timerJson = localStorage.getItem("timeData");
var timerParsed = JSON.parse(timerJson);
console.log(`You spent ${timerParsed.time} seconds on previous page`)
}
else{
console.log("Reload the page and see how much time you spent reading this.")
}
}
//Trig function when page opens.
window.onload = start();
//Before page reloads, store timeSpent in localStorage as a Json file.
var timeData = {
time: timeSpent,
}
function storeData (timeData){
var timerJson = JSON.stringify(timeData)
localStorage.setItem("timeData", timerJson);
}
window.onbeforeunload = storeData (timeData)
Thanks!