JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.jsdelivr.net/jquery.cookie/1.3.1/jquery.cookie.js"></script>
<div id="counter"></div>
CSS
div {
font-size: 32px;
display: inline-block
}
JavaScript
var timeToPass = 9000;
function setCounter(c) {
var timeout = timeToPass - c,
hours = Math.floor(timeout/3600),
minutes = Math.floor(timeout%3600/60),
seconds = timeout%60;
$('#counter').text([hours + ' hours', minutes + ' minutes', seconds + ' seconds to go'].join(', '));
}
/* get the last time the user visited the page */
var lastTime = parseInt(($.cookie('timepassed') || new Date().getTime()), 10);
var timeAway = parseInt((new Date().getTime() - lastTime) / 1000, 10);
var timeElapsed = parseInt(($.cookie('mytimeout') || 0), 10);
/* add elapsed time to the count. If the count is negative, set it to 0 */
var count = Math.min(timeElapsed + timeAway, timeToPass);
/* set an interval that adds seconds to the count */
setCounter(count);
var interval = setInterval(function () {
count++;
setCounter(count);
/* plus, you can do something you want to do every second here,
like display the countdown to the user */
}, 1000);
/* set a timeout that expires 900000 Milliseconds (15 Minutes) -
the already passed time from now */
var timeout = setTimeout(function () {
/* put here what you want to do once the timer epires */
}, timeToPass * 1000 - count * 1000);
/* before the window is reloaded or closed, store the current timeout in a cookie.
For cookie options visit jquery-cookie */
window.onbeforeunload = function () {
$.cookie('mytimeout', count, {
expires: 7,
path: '/'
});
$.cookie('timepassed', new Date().getTime(), {
expires: 7,
path: '/'
});
};