elton73
elton73

Reputation: 473

Wait for JavaScript function to finish before proceed

This might not be a complicated question but I'm not sure if I'm on the right track here.

My goal is to run a JavaScript function first and when the execution is completely finished (this may take up to a few seconds, but not always) close the window.

The function and closing is triggered by just 1 button:

<button id="myID">Click me</button>

The JavaScript is:

<script type="text/javascript">
    function someFunction() {
        // do some stuff
    }

    document.getElementById('myID').addEventListener("click", function(){
        someFunction();
        window.close();
    });
</script>

This works fine, but can get anyone give some advice if this is a reliable method or not? It is important that execution of the function is fully completed before window.close() is triggered.

Upvotes: 0

Views: 1282

Answers (4)

Jonathan Gagne
Jonathan Gagne

Reputation: 4379

You can put your window.close() right under your alert();. However, if you would like to add more asynch stuff, you want a callback function like this.

<script type="text/javascript">
    var closeWindow = function() {
        window.close();
    };

    function someFunction(callback) {
        alert('hi');
        callback();
    }

    document.getElementById('myID').addEventListener("click", function(){
        someFunction(closeWindow);
    });
</script>

Upvotes: 4

Jonas Wilms
Jonas Wilms

Reputation: 138267

someFunction() does some DOM manipulation after a page has loaded

Thats synchronous (the browser might defer the rendering, but were talking about milliseconds here), and therefore it is guaranteed that the DOM manipulation is done before the function returns.

Upvotes: 0

vicbyte
vicbyte

Reputation: 3790

Synchronous javascript will always be run in the top-down order and will always guarantee that instruction one will be finished before instruction two.

But, there is also an asynchronous part (you don't have it here, but for example ajax requests are often asynchronous), that is executed differently and requires callbacks/promises.

Upvotes: 2

Alexander Dimitrov
Alexander Dimitrov

Reputation: 974

Your options are:

  1. put window.close(); in the callback function
  2. use promises this way you can control if the callback execution /if there is an error you can handle it better and not close the window/

Upvotes: 0

Related Questions