1

In the below code second alert comes before the first print pop page. Search results says window.print is a OS functionality and it does not have return value.

Second alert should come only after the print popup. Kindly help

<script>
    function myFunction() {
        for(i=0;i<6;i++){
            alert('Printing Copy:'+i);
            window.print();
        }
    }
</script>
Bindiya Patoliya
  • 2,726
  • 1
  • 16
  • 15

1 Answers1

0

window.print is an asynchronous function. "Asynchronous" means that the execution will immediately return to the calling function, and whatever that is expected to be done by the function will happen in another time.

What happens in your case is this: You are looping several times, and each time you are alerting the user that you are going to print the document, and then you call print. However, the print call will immediately return, and your loop will get to the second iteration before it pops up the print dialog for the first iteration.

As a remedy, you can use onbeforeprint to alert the user that you are going to print the document.

function myFunction() {
    for(i=0; i<6; i++){
        window.onbeforeprint = function(){
            alert("Printing copy:" + i);
        }

        window.print();
    }
}

Note: If you do not understand how this code works, you may want to search and learn a bit about "JavaScript closures", "callbacks", and "asynchronous functions".

sampathsris
  • 21,564
  • 12
  • 71
  • 98