JSFiddle - React, Tailwind, and code Playground
by eklingen
HTML
<div id="timer"></div>
JavaScript
var timer = document.getElementById('timer');
var tickInterval = setInterval(tick, 1000);
var alertThreshold = 5;
var remainingTime = 6;
var prompted = false;
function tick() {
timer.innerHTML = remainingTime + ' seconds remaining';
if( remainingTime <= 0 ) {
alert('Your time has expired.');
clearInterval(tickInterval);
} else if( remainingTime <= alertThreshold ) {
timer.style.color = '#f00';
if( !prompted ) {
prompted = true;
var addTime = parseInt(prompt('This session will expire in ' + remainingTime + ' seconds. If you want to extend your remaining time, enter the number of seconds below'));
if( addTime ) {
remainingTime += addTime;
prompted = false;
}
}
} else {
timer.style.color = '#000';
}
remainingTime--;
}