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 alert
ing 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".