Wednesday, December 19, 2007

Javascript sleep() or wait() in Sahi

My previous post on 'Javascript sleep() or wait()' is visited a lot of times and I think I should write how the problem was eventually solved in Sahi.

Sahi needs to playback scripts written in javascript on the browser.
Let us consider a small example:

We are trying to automate an AJAXy mail client application which has an Inbox button, which when clicked, loads a part of the page, and this newly loaded content has a link 'Unread'.


_click(_button('Inbox'));
_click(_link('Unread'));


When the first line is executed, the Inbox button gets clicked and the script has to wait till the relevant portions of the page load, before it can click 'Unread'.

To solve this, Sahi has a script parser which modifies this script to look something like this:


steps = new Array();
steps[steps.length] = "_click(_button('Inbox'));";
steps[steps.length] = "_click(_link('Unread'));";


And to execute these steps, it does:


var currentStep = 0;
function execute(){
if (currentStep == steps.length) return;
window.eval(steps[currentStep]);
currentStep++;
window.setTimeout('execute()', 1000);
}

execute();


Hope this helps people who are looking for a solution for javascript sleep.

2 comments:

Anonymous said...

Thank you very much, it was solved my problem!!!

Abe said...

I actually came to this page looking for the following solution:

http://sahi.co.in/w/_wait
_wait(1000, _byId("my-div").innerHTML!="")

This will wait for the my-div container to contain html for up to 1 second before continuing the script.