SetInterval and this.wait in casper.js

I need to do a loop 3 times and 2 seconds between each iteration . I tried these 3 options:

Option 1

var casper = require('casper').create({ verbose: false, logLevel: 'debug' }); casper.start("http://google.com"); casper.on('remote.message', function(msg) { this.echo('remote message caught: ' + msg); }) casper.thenEvaluate(function() { var x = 0; var intervalID = setInterval(function () { console.log("Using setInternal " + x); if (++x === 3) { window.clearInterval(intervalID); } }, 2000); }); casper.run(); 

Observation: nothing appeared because the script ended right before the first setInterval called.

Option 2

Replaced thenEvaluate() with then() below

 for (i=0; i<3; i++) { this.wait(2000); this.echo('Using this.wait ' + i); } 

Observation: it gives out 3 times at once, and then a long wait, since this.wait() is asynchronous. This is not what I want, because I need a delay between them.

Option 3 Replace the part in then() as follows. I was thinking of making a recursive call to waitFunc() after calling wait() .

 var count = 0; var waitFunc = function() { this.wait(2000, function() { if (count < 3) { casper.echo('Using this.wait ' + count); count++; waitFunc(); } }); }; 

Observation: nothing is printed on the screen.

So my question is: How do I make this.wait or setInterval work in the loop 3 times, like this case

+5
javascript phantomjs webkit casperjs qtwebkit
source share
1 answer

Here is an example implementation to solve your problem:

 var casper = require('casper').create(); var last, list = [0, 1, 2, 3]; casper.start("http://google.fr/", function() { this.echo('google'); }); casper.on('remote.message', function(msg) { this.echo('remote message caught: ' + msg); }); casper.thenEvaluate(function() { window.x = 0; var intervalID = setInterval(function() { console.log("Using setInternal " + window.x); if (++window.x === 3) { window.clearInterval(intervalID); } }, 500); }); casper.each(list, function(self, i) { self.wait(500, function() { last = i; this.echo('Using this.wait ' + i); }); }); casper.waitFor(function() { return last === list[list.length - 1] && 3 === this.getGlobal('x'); }, function() { this.echo('All done.').exit(); }); casper.run(function() {}); 

Output Example:

 $ casperjs test.js google remote message caught: Using setInternal 0 Using this.wait 0 remote message caught: Using setInternal 1 Using this.wait 1 remote message caught: Using setInternal 2 Using this.wait 2 Using this.wait 3 All done. $ 
+14
source share

All Articles