setInterval and this.在casper.js中[英] setInterval and this.wait in casper.js

问题描述

我需要在每次迭代之间进行 3次和2秒的循环.我尝试了这3个选项:

选项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();

观察:什么都没有出现,因为脚本在第一个setInterval被称为之前立即结束.

选项2

thenEvaluate() thenEvaluate() then()

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

观察:它立即输出3次,然后长时间等待,因为this.wait()是异步.这不是我想要的,因为我想延迟介于两者之间.

选项3 在以下内容中替换then()中的零件.我正在考虑在每次wait()被调用后对waitFunc()进行递归电话.

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

};

观察:屏幕上没有打印出来.

所以我的问题是:如何使此.

推荐答案

这是解决您的问题的示例实现:

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() {});

样本输出:

$ 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.
$

本文地址:https://www.itbaoku.cn/post/1739938.html