0

var documentURLs = ["maca.pdf", "maca2.pdf"]
function printDocuments(index){
   if(index > documentURLs.length){
        return;
   }
   else {
     printJS({
       printable: documentURLs[index],
       type: 'pdf',
       onPrintDialogClose: function () {
         console.log(index);
          printDocuments(index++)
       }
     })
   }
}
<button type="button" onclick="printDocuments(0)">Print</button>

This is not incrementing the index, always print first document and it is not stopping

maca
  • 480
  • 3
  • 12
  • 2
    `index++` means "use the current value of `index`, and then increment it by 1". I think if you change it to `++index` it would work how you'd expect - "increment `index` by one, and then use that value` – WOUNDEDStevenJones Nov 15 '21 at 21:58

1 Answers1

3

It behaves exactly as it should. If you want to call printDocuments with the next index, you should use printDocument(++index) or justprintDocument(index+1), because it's the least confusing one. i++ returns current value of i and then adds 1. ++i first adds 1 and returns that increased value (so i+1).

paolostyle
  • 1,849
  • 14
  • 17
  • Pedantic, but generally `++index` is not quite the same as `index+1`, because the first way also increments its value, while the second only returns the value `index + 1`. Though _in this case_ it's the same because they're not doing anything with `index` afterwards. – WOUNDEDStevenJones Nov 15 '21 at 22:01
  • I never said it's the same. It's just in this case incrementing operator, regardless if used as a postfix or prefix introduces unneeded complexity, IMO. – paolostyle Nov 15 '21 at 22:03
  • Yup, just clarifying. I didn't mean to imply you were saying they're the same. :) – WOUNDEDStevenJones Nov 15 '21 at 22:04