JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Acme Bank</h1>
<div id="warning" style="display: none;">
<p>Time before finish session: <span></span></p>
<p>
<button type="button" id="close">Close</button>
<button type="button" id="notClose">Not close</button>
</p>
</div>
JavaScript
var timeOfLastActivity;
var timeForCloseSession;
var timeBeforeWarning = 5000; // 5 seconds
var timeBeforeClose = 10000; // 10 seconds
var timeForUpdateWarning = 500; // 0.5 seconds
function resetAll() {
timeOfLastActivity = new Date().getTime();
timeForCloseSession = timeOfLastActivity + timeBeforeClose;
setTimeout(function() {
$("#warning").show();
showTime();
}, timeBeforeWarning);
$("#warning").hide();
}
function showTime() {
var currentTime = new Date().getTime();
if (currentTime < timeForCloseSession) {
$("#warning span").html(timeForCloseSession - currentTime)
} else {
$("#close").trigger("click");
}
if ($("#warning").is(":visible")) {
setTimeout(showTime, timeForUpdateWarning);
}
}
$("#close").click(function() {
$("#warning").hide();
$("h1").html("Session closed");
$.post("/echo/json/"); // Send AJAX close
});
$("#notClose").click(function() {
resetAll();
$.post("/echo/json/"); // Send AJAX beat
});
resetAll();