title: JavaScript/CasperJS handling of timeouts when looping over pages
body: <p>I have a problem with this script. It is supposed to load some links (line by line) saved in prova.txt then pass the links one by one to CasperJS and get the html of the page. I know that there must be some problem with timeouts/JavaScript.</p>
  
  <p>Here is the script:</p>
  
  <pre><code>var fs = require('fs');
  var file_h = fs.open('prova.txt', 'r');
  var line = file_h.readLine();
  var links = new Array();
  var casper = require('casper').create();
  
  while(line) {
      line = file_h.readLine();
      links.push(line);
  }
  
  (function theLoop (i) {
      console.log("LOOP");
      casper.start(links[i], function() {
          setTimeout(function () {
              fs.write("stats" + i + ".html", this.getHTML() );
              i = i + 1;
              if (--i) {
                  theLoop(i);
              }
          }, 2000);
      });
      casper.run();
  })(4);
  </code></pre>
  
  <p>Documentation that I used: <a href="http://scottiestech.info/2014/07/01/javascript-fun-looping-with-a-delay/" rel="nofollow">http://scottiestech.info/2014/07/01/javascript-fun-looping-with-a-delay/</a></p>