Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript open a windows after a delay then close it after another delay

I try to create a javascript function that, when user clicks on a button, opens a new tab after a small timeframe then wait one second and close it.

Currently, my code looks like this:

var btn = document.getElementById("myLink");
btn.onclick = function() {
    setTimeout(function() {
        var win = window.open(
        "http://www.stackoverflow.com", 
        "The new Link")
    },500);
    setTimeout(function(){
            win.close();
        if (win.closed) {
            clearInterval(timer);
            winClosed();
            alert("'The new Link' window closed !");
        }
    }, 2500);
}

but the second setTimeout function is not executed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I remove one of the two setTimeout function, the other one works fine, but I need to have the two running.

edit: change timeout values to take into account lk77 comment.

>Solution :

There are 2 issues in your code.

  1. you are initializing the variable win in the first timeout, meaning it will not be available in the second timeout. You might want to read about closure & scoping in javascript.
  2. Your first timeout has a delay of 1500 ms and the second one 500, meaning that the second timeout fires before the first one.

This should be working:

var btn = document.getElementById("myLink");
btn.onclick = function() {
    var win = null; // initialize here so it is available in both timeouts
    setTimeout(function() {
        win = window.open( // set the value here
        "http://www.stackoverflow.com", 
        "The new Link")
    },500); // this should fire first
    setTimeout(function(){
            win.close();
        if (win.closed) {
            clearInterval(timer);
            winClosed();
            alert("'The new Link' window closed !");
        }
    }, 1500); // this should fire second
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading