AsyncCalls and Internet Explorer / JavaScript

A friend of mine asked me recently if I knew of an elegant way to handle asynchronous calls in Internet Explorer. Basically the problem starts with some event like “load a page” then “do something” after the page is done loading. With the emergence of AJAX-style applications which exploit this asynchronous behavior quite heavily, it's interesting to have some way to write code that handles async calls. This is especially true if you want to write automated test scripts.

In any case, I sat down this morning and wrote up the following. It's only the solution. I'll let you work out how to integrate it in with a real problem:

function AsyncCall(action, condition, callback, timeout) {
  action();
  window.setTimeout("onTimer(" + condition + ", " + callback + ", " + timeout + ")", timeout);
}

function onTimer(condition, callback, timeout) {
  if (condition()) {
    callback();
  }
  else {
    window.setTimeout("onTimer(" + condition + ", " + callback + ")", timeout);
  }
}

You would then introduce a call like:

AsyncCall(setUrl, checkFrame, notifyDone, 100);

This invokes the “action“ function, then periodically checks the “condition“ function. When the condition returns true, then it calls the “callback“ function.

Here's a simple web page that lets you set the SRC property of an IFrame, then notifies you when the page is completely loaded:

<html>
<head>
<title>Async Test</title>
</head>
<script language="JScript" src="asynccall.js"></script>
<script language="JScript">
function updatePage() {
  AsyncCall(setUrl, checkFrame, notifyDone, 100);
}
function setUrl() {
  document.all["myFrame"].src=myForm.url.value;
}
function checkFrame() {
  return document.all["myFrame"].readyState == "complete";
}
function notifyDone() {
  alert("Done!");
}
</script>
<body>
<form id="myForm">
<input type="text" name="url" />
<input type="button" value="Go" onClick="updatePage()" />
</form>
<iframe id="myFrame" src="about:blank" height="100%" width="100%"></iframe>
</body>

Happy async calling!

-Doug


Posted Jul 28 2006, 09:02 AM by doug-walter

Comments

Joshua Flanagan wrote re: AsyncCalls and Internet Explorer / JavaScript
on 07-28-2006 3:32 PM
I believe Selenium (since you mention automated testing...) has a very similar feature. Check out:
http://wiki.openqa.org/display/SEL/waitForCondition
Jason Haley wrote Interesting Finds: July 28, 2006
on 07-28-2006 10:27 PM
Jason Haley wrote Interesting Finds: July 28, 2006
on 07-28-2006 10:30 PM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?