Auto Closing Alert Box

Simulating an alert box with a window.open popup and then closing it

by woold

HTML

<!DOCTYPE html>
<html>
<body>

<p>Click the button to write to open an "alert" which will automatically closesome seconds later.</p>

<label for="msg">Message:</label>
<input id="msg" value="Hey hope this solves the problem">
<br>
<label for="title">Title:</label>
<input id="title" value="alert!">
<br>
<label for="width">Width:</label>
<input id="width" value="200">
<br>
<label for="height">Height:</label>
<input id="height" value="100">
<br>
<label for="timeout">Timeout (milliseconds):</label>
<input id="timeout" value="5000">
<br>
<br>
<button onclick="myAlert(`Hey hope this solves the problem`,`alert!`,200,100)">Try it</button>

<script>
function myAlert(msg,title,width,height,timeout) {
		msg = document.querySelector("#msg").value;
		title = document.querySelector("#title").value;
		width = document.querySelector("#width").value;
		height = document.querySelector("#height").value;
		timeout = document.querySelector("#timeout").value;
    var timer = Date.now()/1000+timeout/1000;
    var myWindow = window.open("", "", `width=${width},height=${height},left=${(window.outerWidth/2-width/2)},top=0`);
    myWindow.document.write(`<center id="msg">`+msg+`</center>`);
    var int = setInterval(function(){
        if (timer-Date.now()/1000>0) {
            myWindow.document.getElementById('msg').innerText = msg+", this will close in "+Math.ceil(timer-Date.now()/1000)+" seconds";
        } else {
            clearInterval(int);
        }
    },0)
    myWindow.document.title = title;
    setTimeout(function(){
        myWindow.close();
    },timeout||5000)
}
myAlert(`Hey hope this solves the problem`,`alert!`,200,100)
</script>

</body>
</html>