setTimeout
events are not treated while a confirm
dialog is open. This is in line with the documentation at WHATWG:
- Pause until the user responds either positively or negatively.
The same specification explains what "Pause" means:
- Wait until the condition goal is met. While a user agent has a paused task, the corresponding event loop must not run further tasks, and any script in the currently running task must block.
So, you would need to implement your own, non-blocking, mechanism, or use one of the many libraries that offer such a feature.
Here is a simple implementation without library, using a Promise-mechanism:
function myConfirm(msg, timeout) {
const inputs = [...document.querySelectorAll("input, textarea, select")].filter(input => !input.disabled);
const modal = document.getElementById("modal");
const elems = modal.children[0].children;
function toggleModal(isModal) {
for (const input of inputs) input.disabled = isModal;
modal.style.display = isModal ? "block" : "none";
elems[0].textContent = isModal ? msg : "";
}
return new Promise((resolve) => {
toggleModal(true);
elems[1].onclick = () => resolve(true);
elems[2].onclick = resolve;
setTimeout(resolve, timeout);
}).then(result => {
toggleModal(false);
return result;
});
}
function refreshToken(){
var r = myConfirm("Your session is about to expire. Click OK to continue or Cancel to log out. Defaulting to Cancel after 4 seconds...", 4000);
return r.then(ok => {
if (ok) {
console.log("extending the session");
// do whatever is needed to extend the session
} else {
console.log("logging out");
//this.logout();
}
return ok;
});
}
// Demo: let the popup appear after 1 second:
setTimeout(refreshToken, 1000);
#modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background: rgb(0,0,0);
background: rgba(0,0,0,0.4);
font-family: "ms sans serif", arial, sans-serif;
}
#modal > div {
position: fixed;
padding: 10px;
width: 280px;
left: 50%;
margin-left: -150px;
top: 50%;
margin-top: -50px;
background: white;
border: 2px outset;
}
<div id="modal">
<div>
<div></div><br>
<button>OK</button>
<button>Cancel</button>
</div>
</div>
<p> This is a test page with a test input </p>
<input>
So you need to add the CSS and the <div id="modal">
element in your HTML. Then call the function myConfirm
with 2 arguments:
- the text to display
- the timeout in milliseconds after which it will be as if the user clicked Cancel
The myConfirm
function returns a promise, so you must await its resolution before you can know and deal with the user-response. For example, use then
to execute your custom code.