Auto Closing Alert Box

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

by dying_sakura

HTML

<button onclick="myAlert(`Hey hope this solves the problem`,`alert!`,200,100)">Try it</button>

<script>
function myAlert(msg,title,width,height,timeout) {
		msg = "Hey hope this solves the problem";
		title = "alert!";
		width = 200;
		height = 100;
		timeout = 5000;
    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>