onbeforeunload event not staying at current page in IE

I am working on primefaces v5 application, if user change something in the form and clicked on some other command button which causes page navigation, need to show warning message.

For that I am using onunloadevent it’s working in chrome/IE for other links like Hyperlinks there is only one time warning message,
but, it’s not working correctly when I click on primefaces command button(like cancel button)

Here is my work:

var isInputChanged = false;

        function activateInputChanges() {
            isInputChanged = true;
        }
        $(document).ready(function() {
            $("#myform").on("change", ":input", function() {
                isInputChanged = true;
            })

            window.addEventListener( 'beforeunload', function(ev) { 
                if(isInputChanged){
                    return ev.returnValue = 'Do you really want to close?';
                } 
            })
        });

If I use this , alert message is coming two times, so to suppress the second time alert I used the below code,

    function activateInputChanges() {
            isInputChanged = true;
        }
        $(document).ready(function() {
            $("#myform").on("change", ":input", function() {
                isInputChanged = true;
            })

            window.addEventListener( 'beforeunload', function(ev) { 
                if(isInputChanged){
                    isInputChanged = false;
                    setTimeout(activateInputChanges, 100);
                    return ev.returnValue = 'Do you really want to close?';
                } else{
                    return undefined;
                }
            })
        });

Now the second alert is not coming, but flow is not staying at current page, it’s going to another page.

How to handle this situation? Thanks in advance !!!!