Skip to content

Instantly share code, notes, and snippets.

@michaelmob
Created September 13, 2015 04:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelmob/c4f5c386241da827f940 to your computer and use it in GitHub Desktop.
Save michaelmob/c4f5c386241da827f940 to your computer and use it in GitHub Desktop.
Phantomjs functions in a sequence instead of the awful nesting.
var Sequence = function() {
this.iter = 0;
this.funcs = [];
this.waitFor = function(testFx, onReady, onTimeOut, timeOutMillis) { // Modified!!!
/* https://github.com/ariya/phantomjs/blob/master/examples/waitfor.js
view github page for credits */
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
typeof(onTimeOut) === "string" ? eval(onTimeOut) : onTimeOut(); //< Do what it's supposed to do once if the condition times out
__sequenceSelf.__run();
} else {
// Condition fulfilled (timeout and/or condition is 'true')
typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
}
clearInterval(interval); //< Stop this interval
}
}, 250); //< repeat check every 250ms
};
Sequence.prototype.add = function(func, timeOutMillis) {
// Add Function to Sequence items
this.funcs.push(func);
return this;
};
this.nextIf = function(testFx, onTimeOut, timeOutMillis) {
if(onTimeOut == undefined)
onTimeOut = phantom.exit;
this.waitFor(testFx, this.__run, onTimeOut, timeOutMillis);
return "__continue__";
};
this.nextContinue = function(testFx, timeOutMillis) {
return this.nextIf(testFx, this.__run, timeOutMillis);
};
this.replay = function() {
// Decrease iteration and re-run
this.iter--;
};
this.run = function() {
if(this.iter > this.funcs.length - 1) {
phantom.exit();
}
var iter = this.iter;
this.iter++;
// Run next sequence script and add iter
if(this.funcs[iter]() != "__continue__") {
this.run();
}
};
// Run annonymously
var __sequenceSelf = this;
this.__run = function() {
__sequenceSelf.run();
};
};
(function() {
var sequence = new Sequence();
sequence
.add(function() {
console.log("Next 1");
return sequence.nextIf(
function() {
// Test Failed
return false
},
function() {
// Timeout
}, 3000 // Timeout
);
})
.add(function() {
console.log("Next 2");
// Continue even if failure
return sequence.nextContinue(
"1==2"
);
});
sequence.run();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment