Execute statement after return statement in Javascript

You can't execute anything after a return statement.

edit: the finally statement allows code execution after a return for cleanup purposes.

(This is a good example for an XY-Question: You are asking about Y while never telling us for what X you actually need it).


The return statement ends a function, you cannot execute code after it. You could do this:

ret = "You are logged out.";
Logout();
return ret;

What you need is to execute Logout asynchronously. This can be easily achieve in JavaScript by using the setTimeout function as others have said. Here's a method I commonly use to call functions asynchronously:

Function.prototype.async = function () {
    setTimeout.bind(null, this, 0).apply(null, arguments);
};

This method pushes a function call onto the event loop immediately (after 0 ms). Hence the function is executed after the current code completes (which for you is after you return). Here's a simple example of how to use it:

alert.async("This will be displayed later.");
alert("This will be displayed first.");

Since the first alert is called asynchronously it will execute after the second call to alert. As simple as preceding your function call with async. This is what you would do in your case:

window.onbeforeunload = function () {
    if (document.getElementById("parentpan").style.display === "block") {
        Logout.async();
        return "You are logged out.";
    }
};

What's the disadvantage? Since the function is blocked on the event loop it may never get the chance to execute (hence the user will never logout). Such a situation may arise. It usually occurs when the control goes into an infinite loop, or hangs because of a blocking AJAX request.

Good news for you however, this happens on a very rare occasion. So don't worry about it. Just use setTimeout like everyone else is bantering you to and you'll do just fine. Personally I think you should log out before returning a message that "You are logged out.", but it's your application.

Happy New Year. Cheers!